Professional Documents
Culture Documents
El and JSTL
El and JSTL
Pradeep LN,
www.clearsemantics.com
3.1
Agenda
Useoftheexpressionlanguage p g g
Understandingthebasicsyntax
Referencingscopedvariables
Accessingbeanproperties,arrayelements,List
elements,andMapentries
Usingexpressionlanguageoperators
E l i i di i ll Evaluatingexpressionsconditionally
EL and J STL
Pradeep LN,
www.clearsemantics.com
3.2
presentingtheresultsintheJSPpage.
jsp useBeanandjsp getPropert jsp:useBeanandjsp:getProperty
Clumsyandverbose
Cannotaccessbeansubproperties
JSPscriptingelements
Resultinhardtomaintaincode
presentingtheresultsintheJSPpageusingEL.
Moreconciseaccess
Abilitytoaccesssubproperties
SimplesyntaxaccessibletoWebdevelopers
Example
Injsp
<jsp:useBeanid="someName"type="somePackage.someClass"
scope="request,session,orapplication"/>
<jsp:getPropertyname="someNameproperty="someProperty"/>
To:
${someName.someProperty}
EL and J STL
Pradeep LN,
www.clearsemantics.com
3.3
Advantagesofthe
ExpressionLanguage
Conciseaccesstostoredobjects.
Tooutputascopedvariable(objectstoredwithsetAttributeinthe
PageContext,HttpServletRequest,HttpSession,orServletContext)
namedsaleItem,youuse${saleItem}.
Shorthandnotationforbeanproperties.
TooutputthecompanyNameproperty(i.e.,resultofthe
getCompanyNamemethod)ofascopedvariablenamedcompany,
youuse${company.companyName}.ToaccessthefirstName
propertyofthepresidentpropertyofascopedvariablenamed
company youuse${company president firstName} company,youuse${company.president.firstName}.
Simpleaccesstocollectionelements.
Toaccessanelementofanarray,List,orMap,youuse
${variable[indexOrKey]}.Providedthattheindexorkeyisinaform
thatislegalforJavavariablenames,thedotnotationforbeansis
interchangeablewiththebracketnotationforcollections.
Succinctaccesstorequestparameters,cookies,andotherrequest
d t data.
Toaccessthestandardtypesofrequestdata,youcanuseoneofseveral
predefinedimplicitobjects.
Asmallbutusefulsetofsimpleoperators.
TomanipulateobjectswithinELexpressions,youcanuseanyofseveral
arithmetic,relational,logical,oremptytestingoperators.
Conditionaloutput.
Tochooseamongoutputoptions,youdonothavetoresorttoJavascripting
elements.Instead,youcanuse${test?option1:option2}.
Automatictypeconversion.
Theexpressionlanguageremovestheneedformosttypecastsandformuch
ofthecodethatparsesstringsasnumbers.
Emptyvaluesinsteadoferrormessages.
Inmostcases,missingvaluesorNullPointerExceptionsresultinempty
strings,notthrownexceptions.
EL and J STL
Pradeep LN,
www.clearsemantics.com
3.4
ELsyntax
${expression}
Th EL l t i di t t i JSPt tt ib t id dth t TheseELelementscanappearinordinarytextorinJSPtagattributes,providedthat
thoseattributespermitregularJSPexpressions.Forexample:
<UL>
<LI>Name:${expression1}
<LI>Address:${expression2}
</UL>
<jsp:includepage="${expression3}"/>
TheELintagattributes
Youcanusemultipleexpressions(possiblyintermixedwithstatictext)andthe
resultsarecoercedtostringsandconcatenated.Forexample:
<jsp:includepage="${expr1}blah${expr2}"/>
AccessingScopedVariables
${varName}
Meanstosearchthe
PageContext,theHttpServletRequest,theHttpSession,andthe
ServletContext,inthatorder,andoutputtheobjectwiththat
attributename.
Equivalentforms
${name}
<%=pageContext.findAttribute("name")%>
<jsp:useBeanid="nametype="somePackage.SomeClassscope="...">
<%=name%>
EL and J STL
Pradeep LN,
www.clearsemantics.com
3.5
AccessingScopedVariables
publ i c cl ass ScopedVar s ext ends Ht t pSer vl et {
publ i c voi d doGet ( Ht t pSer vl et Request r equest Ht t pSer vl et Response publ i c voi d doGet ( Ht t pSer vl et Request r equest , Ht t pSer vl et Response
r esponse) t hr ows Ser vl et Except i on, I OExcept i on {
request.setAttribute("attribute1", "First Value");
Ht t pSessi on sessi on = r equest . get Sessi on( ) ;
session.setAttribute("attribute2", "Second Value");
Ser vl et Cont ext appl i cat i on = get Ser vl et Cont ext ( ) ;
application.setAttribute("attribute3",new java.util.Date());
request.setAttribute("repeated", "Request");
i tAtt ib t (" t d" "S i ") session.setAttribute("repeated", "Session");
application.setAttribute("repeated", "ServletContext");
Request Di spat cher r d =r equest . get Request Di spat cher ( "scopedvar s. j sp" ) ;
r d. f or war d( r equest , r esponse) ;
}
}
scopedvars.jsp
<TABLE BORDER=5 ALI GN=" CENTER" >
<TR>
<TH CLASS=" TI TLE" >Accessi ng Scoped Var i abl es
</ TABLE> </ TABLE>
<P><UL>
<LI ><B>at t r i but e1: </ B> ${at t r i but e1}
<LI ><B>at t r i but e2: </ B> ${at t r i but e2}
<LI ><B>at t r i but e3: </ B> ${at t r i but e3}
<LI ><B>Sour ce of " r epeat ed" at t r i but e:
</ B> ${r epeat ed}
</ UL>
</ BODY></ HTML>
EL and J STL
Pradeep LN,
www.clearsemantics.com
3.6
AccessingBeanProperties
${varName.propertyName} ${varName.propertyName}
Meanstofindscopedvariableofgivennameandoutput
thespecifiedbeanproperty
Example:
<body>
Hello+${customer.firstName}
</body>
AccessingBeanProperties(Contd..)
${customer.firstName}
Equivalentforms
<%@page i mpor t =com. NameBean%>
<%NameBean per son
( NameBean) pageCont ext . f i ndAt t r i but e( cust omer ) ; %>
<%= per son. get Fi r st Name( ) %>
Or Or
<j sp: useBean i d=cust omer t ype=com. NameBean
scope=request, session, or application / >
<j sp: get Pr oper t y name=cust omer pr oper t y=f i r st Name/ >
EL and J STL
Pradeep LN,
www.clearsemantics.com
3.7
Example:AccessingBeanProperties
publ i c cl ass BeanPr oper t i es ext ends Ht t pSer vl et {
publ i c voi d doGet ( Ht t pSer vl et Request r equest Ht t pSer vl et Response r esponse) publ i c voi d doGet ( Ht t pSer vl et Request r equest , Ht t pSer vl et Response r esponse)
t hr ows Ser vl et Except i on, I OExcept i on {
NameBean name = new NameBean(PDP",LN");
CompanyBean company =new
CompanyBean(pratian","J2EE Training and Consulting");
EmployeeBean employee =new EmployeeBean(name, company);
request.setAttribute("employee", employee);
R t Di t h di t h t t R t Di t h ( "b Request Di spat cher di spat cher = r equest . get Request Di spat cher ( "bean-
pr oper t i es. j sp" ) ;
di spat cher . f or war d( r equest , r esponse) ;
}
}
Example:AccessingBeanProperties
publ i c cl ass Empl oyeeBean {
private NameBean name;
private CompanyBean company;
public EmployeeBean(NameBean name, CompanyBean company) { p p y ( , p y p y)
set Name( name) ;
set Company( company) ;
}
publ i c NameBean get Name( ) { r et ur n( name) ; }
publ i c voi d set Name( NameBean newName) {name = newName; }
publ i c CompanyBean get Company( ) { r et ur n( company) ; }
publ i c voi d set Company( CompanyBean newCompany) {company = newCompany; }
public class NameBean {
private String firstName;
private String lastName;
public class CompanyBean {
private String companyName;
private String business; private String lastName;
public NameBean(String first,String last)
{
setFirstName(first);
setLastName(last);}
public String getFirstName()
{return(firstName);}
public void setFirstName
(String FirstName)
{firstName = newFirstName;}
.
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;
}
..
EL and J STL
Pradeep LN,
www.clearsemantics.com
3.8
Example:AccessingBeanProperties
<!DOCTYPE>
UL <UL>
<LI><B>FirstName:</B>
${employee.name.firstName}
<LI><B>LastName:</B>
${employee.name.lastName}
<LI><B>CompanyName:</B>
${employee.company.companyName}
<LI><B>CompanyBusiness:</B> <LI><B>CompanyBusiness:</B>
${employee.company.business}
</UL>
</BODY>
</HTML>
Accessing Collections
${attributeName[entryName]} { [ y ]}
Array.Equivalentto
theArray[index]
List.Equivalentto
theList.get(index)
Map.Equivalentto
h M (k N ) theMap.get(keyName)
Equivalentforms(forHashMap)
${stateCapitals["maryland"]}
${stateCapitals.maryland}
EL and J STL
Pradeep LN,
www.clearsemantics.com
3.9
Example:AccessingCollections
publ i c cl ass Col l ect i ons ext ends Ht t pSer vl et {
publ i c voi d doGet ( Ht t pSer vl et Request r equest , Ht t pSer vl et Response r esponse) p ( p q q , p p p )
t hr ows Ser vl et Except i on, I OExcept i on {
String[] firstNames = { "Bill", "Scott", "Larry" };
ArrayList lastNames = new ArrayList();
lastNames.add("Ellison");
lastNames.add("Gates");
lastNames.add("McNealy");
HashMap companyNames = new HashMap();
companyNames.put("Ellison", "Sun");
companyNames.put("Gates", "Oracle");
companyNames.put("McNealy", "Microsoft");
r equest . set At t r i but e( " f i r st " , f i r st Names) ;
r equest . set At t r i but e( " l ast " , l ast Names) ;
r equest . set At t r i but e( " company" , companyNames) ;
Request Di spat cher di spat cher =
r equest . get Request Di spat cher ( " / el / col l ect i ons. j sp" ) ;
di spat cher . f or war d( r equest , r esponse) ;
}}
Example:AccessingCollections
<! DOCTYPE >
<BODY>
<TABLE BORDER=5 ALI GN=" CENTER" >
<TR><TH CLASS=" TI TLE" >
Accessi ng Col l ect i ons
</ TABLE>
<P>
<UL>
<LI>${first[0]} ${last[0]} (${company["Ellison"]})
<LI>${first[1]} ${last[1]} (${company["Gates"]})
<LI>${first[2]} ${last[2]} (${company["McNealy"]})
</UL>
</ BODY></ HTML>
EL and J STL
Pradeep LN,
www.clearsemantics.com
3.10
Implicitobjects
Example:ImplicitObjects
<!DOCTYPE>
<P>
<UL> <UL>
<LI><B>testRequestParameter:</B> ${param.test}
<LI><B>UserAgentHeader:</B>${header["UserAgent"]}
<LI><B>JSESSIONIDCookieValue:</B>
${cookie.JSESSIONID.value}
<LI><B>Server:</B>${pageContext.servletContext.serverInfo}
</UL>
</BODY>
</HTML> /
EL and J STL
Pradeep LN,
www.clearsemantics.com
3.11
ExpressionLanguageOperators
Arithmetic
+ */div%mod
Relational
==eq!=ne<lt>gt<=le>=ge
Logical
&&and||or!Not
Empty Empty
Empty
Truefornull,emptystring,emptyarray,emptylist,
emptymap.Falseotherwise.
Example:Operators
<TABLE BORDER=1 ALI GN=" CENTER" >
<TR><TH CLASS " COLORED" COLSPAN 2>Ar i t hmet i c Oper at or s <TR><TH CLASS=" COLORED" COLSPAN=2>Ar i t hmet i c Oper at or s
<TH CLASS=" COLORED" COLSPAN=2>Rel at i onal Oper at or s
<TR><TH>Expr essi on<TH>Resul t <TH>Expr essi on<TH>Resul t
<TR ALI GN=" CENTER" >
<TD>\${3+2- 1}<TD>${3+2-1}
<TD>\${1&l t ; 2}<TD>${1<2}
<TR ALI GN=" CENTER" >
<TD>\${" 1" +2}<TD>${"1"+2}
<TD>\${" a" &l t ; " b" }<TD>${"a"<"b"}
<TR ALI GN=" CENTER" >
<TD>\${1 + 2*3 + 3/ 4}<TD>${1 + 2*3 + 3/4}
<TD>\${2/ 3 > ; = 3/ 2}<TD>${2/3 >= 3/2}
<TR ALI GN=" CENTER" >
<TD>\${3%2}<TD>${3%2}
<TD>\${3/ 4 == 0. 75}<TD>${3/4 == 0.75}
EL and J STL
Pradeep LN,
www.clearsemantics.com
3.12
Example:Operators(Result)
EvaluatingExpressionsConditionally
${test?expression1:expression2} ${test?expression1:expression2}
Evaluatestestandoutputseitherexpression1or
expression2
EL and J STL
Pradeep LN,
www.clearsemantics.com
3.13
Example:Conditional Expressions
publ i c cl ass Condi t i onal s ext ends Ht t pSer vl et {
publ i c voi d doGet ( Ht t pSer vl et Request r equest , Ht t pSer vl et Response r esponse)
t hr ows Ser vl et Except i on, I OExcept i on {
SalesBean apples = new SalesBean(150.25, -75.25, 22.25,-
3 57); 3.57);
SalesBean oranges =new SalesBean(-220.25, -49.57,
138.25, 12.25);
request.setAttribute("apples", apples);
request.setAttribute("oranges", oranges);
Request Di spat cher di spat cher =r equest . get Request Di spat cher ( / condi t i onal s. j sp" ) ;
di spat cher . f or war d( r equest , r esponse) ; } }
publ i c cl ass Sal esBean {
pr i vat e doubl e q1, q2, q3, q4;
publ i c Sal esBean( doubl e q1Sal es, doubl e q2Sal es, doubl e q3Sal es, doubl e q4Sal es) {
q1 = q1Sal es; q2 = q2Sal es;
q3 = q3Sal es; q4 = q4Sal es; }
publ i c doubl e get Q1( ) { r et ur n( q1) ; }
publ i c doubl e get Q2( ) { r et ur n( q2) ; }
publ i c doubl e get Q3( ) { r et ur n( q3) ; }
publ i c doubl e get Q4( ) { r et ur n( q4) ; }
publ i c doubl e get Tot al ( ) {r et ur n( q1 + q2 + q3 + q4) ; }
Example:ConditionalExpressions
<TABLE BORDER=1 ALI GN=" CENTER" >
<TR><TH> <TR><TH>
<TH CLASS=" COLORED" >Appl es
<TH CLASS=" COLORED" >Or anges
<TR><TH CLASS=" COLORED" >Fi r st Quar t er
<TD ALI GN=" RI GHT" >${appl es. q1}
<TD ALI GN=" RI GHT" >${or anges. q1}
<TR><TH CLASS=" COLORED" >Second Quar t er
<TD ALI GN=" RI GHT" >${appl es. q2}
<TD ALI GN=" RI GHT" >${or anges. q2}