Download as pdf or txt
Download as pdf or txt
You are on page 1of 24

EL and J STL

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 &gt ; = 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}

<TR><TH CLASS=" COLORED" >Tot al


<TD ALI GN " RI GHT <TD ALI GN=" RI GHT
BGCOLOR="${(apples.total < 0) ? "RED" : "WHITE" }">
${appl es. t ot al }
<TD ALI GN=" RI GHT
BGCOLOR="${(oranges.total < 0) ? "RED" : "WHITE" }">
${or anges. t ot al }
</ TABLE>
EL and J STL
Pradeep LN,
www.clearsemantics.com
3.14
Example:ConditionalExpressions(Result)
EL and J STL
Pradeep LN,
www.clearsemantics.com
3.15
JSTL(JSPStandardTagLibraries) isa
collectionofJSPcustomtagsdevelopedbyJava
WhatIsJSTL?
collectionofJSPcustomtagsdevelopedbyJava
CommunityProcess,
NeedforJSTL
SimplifyJSPpageauthoring SimplifyJSPpageauthoring
ProvideastandardlibraryavailableonanyJSP1.2
container
Makedynamicwebprogrammingmoreaccessibleto
nonJavaprogrammers
EL and J STL
Pradeep LN,
www.clearsemantics.com
3.16
Taglibraries:
MultipleTagLibraries MultipleTagLibraries
Core(c)
XML(x)
Formatting(fmt)
SQL(sql)
MosttagscancreateScopedVariables g p
AllTagsSupportTagBody
JSTLTaglibraries:
Core(c) Core(c)
<%@tagliburi="http://java.sun.com/jstl/coreprefix="c"%>
Writing,creatingscopedvariables,conditional
logic,looping,URLs(import,redirect)
Formatting(fmt)
<%@tagliburi="http://java.sun.com/jstl/fmt"prefix="fmt"%>
Internationali ationandlocali ation Internationalizationandlocalization
Formattingandparsingnumber
EL and J STL
Pradeep LN,
www.clearsemantics.com
3.17
JSTLTaglibraries:
XMLtags(x) XMLtags(x)
<%@tagliburi="http://java.sun.com/jstl/xmlprefix="x"%>
XMLparsing,fragmentselection,flowcontrol(logic),
transforming
Databasetags(sql)
Limitedusefornontrivialapps
Defaultdatasourceimpldoesnotsupportconnection
pooling
CoreTagLibrary
<c:out>
To evaluate an expression and include the
expressions output in the page
<c:outvalue="${p.value}default=Novalueforparameter/>
<%@t agl i b ur i =
" ht t p: / / j ava. sun. com/ j st l / cor e" pr ef i x=" c" %>
<ht ml >
<body>
<c: out val ue=" Hel l o wor l d! " / >
</ body>
</ ht ml >
EL and J STL
Pradeep LN,
www.clearsemantics.com
3.18
CoreTagLibrary
<c:set>
create or modify scoped variable
<c:set var=Name value=${person.firstName} />
<%@t agl i b ur i =
" ht t p: / / j ava. sun. com/ j st l / cor e" pr ef i x=" c" %>
<ht ml >
<body>
<c:setvar="customerIDvalue=1234"scope="session/>
<c:outvalue="${customerID}/>
</ body>
</ ht ml >
CoreTagLibrary
<c:remove>
d bl removesascopedvariable
Scopeisoptional,buttheattributewillberemovedfrom
allscopesifscopeisnotspecified
<%@t agl i b ur i =
" ht t p: / / j ava. sun. com/ j st l / cor e" pr ef i x=" c" %>
<ht ml >
<body>
<c:removevar=customerIDscope=session/>
</ body>
</ ht ml >
EL and J STL
Pradeep LN,
www.clearsemantics.com
3.19
CoreTagLibrary
<c:catch.>
ff h dl h b dd effectivewaytohandleexceptionswithoutembedding
Javacodeinyourpages
<%@t agl i b ur i =
" ht t p: / / j ava. sun. com/ j st l / cor e" pr ef i x=" c" %>
<ht ml >
<body>
<c:catch>
<! JSTLtagsbelowwhichcouldthrowanexception>
</c:catch>
</ body>
</ ht ml >
<c:catch>example
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>
h l <html>
<body>
<c:catch var="signalException">
<%
int i= (int) (Math.random() * 10);
if (i < 5 )
thrownewNullPointerException(); %>
</c:catch>
<c:choose>
<c:when test="${signalException != null}">
Exceptionoccurs.
</c:when>
<c:otherwise> No Exception. </c:otherwise>
</c:choose>
%> </body></html>
EL and J STL
Pradeep LN,
www.clearsemantics.com
3.20
CoreTagLibrary Conditionals
<c:if>
h l ' l h b TheBooleanexpression'svalueinthetestattributeis
evaluated
<%@t agl i b ur i =
" ht t p: / / j ava. sun. com/ j st l / cor e" pr ef i x=" c" %>
<ht ml >
<body> <body>
<c:iftest="${status.totalVisits ==1000000}"var="visits>
Youarethemillionthvisitortooursite!Congratulations!
</c:if>
</ body>
</ ht ml >
CoreTagLibrary Conditionals
<c:choose>
l k f l f l likeanif/elseif/elsestatement
oraswitchstatementwithoutfallthrough
<%@t agl i b ur i =
" ht t p: / / j ava. sun. com/ j st l / cor e" pr ef i x=" c" %>
<ht ml >
<body>
<c:choose>
<c:whentest="${item.type =='book'}></c:when>
<c:whentest="${item.type =='electronics'}></c:when>
<c:whentest="${item.type =='toy'}></c:when>
<c:otherwise></c:otherwise>
</c:choose>
</ body>
</ ht ml >
EL and J STL
Pradeep LN,
www.clearsemantics.com
3.21
CoreTagLibrary Looping
<c:foreach>
h l bl iterateovertheelementsinaniterable:anarray,
Collection,Map,ResultSetoracommaseparatedStrings
<%@t agl i b ur i =
" ht t p: / / j ava. sun. com/ j st l / cor e" pr ef i x=" c" %>
<ht ml >
<body>
<c:forEachvar="item"items="${arrayOfItems}>
<c:outvalue=${item.itemName}/>
<c:outvalue=${item.price}/>
</c:forEach>
</ body>
</ ht ml >
CoreTagLibrary url
<c:url>
ll h k d bl d AllowsURLrewritingwhencookiesaredisabled
<%@t agl i b ur i =
" ht t p: / / j ava. sun. com/ j st l / cor e" pr ef i x=" c" %>
<ht ml >
<body> <body>
<c:urlvalue="http://pratian.com"var="myUrl">
</c:url>
</ body>
</ ht ml >
EL and J STL
Pradeep LN,
www.clearsemantics.com
3.22
ToIncludeContentinJSP
Includedirective
Static(translation
time)
Includedirective
<%@includefile=Header.html%>
jsp:include
<jsp:includepage=Header.jsp/>
Dynamic(requesttime)
j p p g j p
ToIncludeContentusingJSTL
<c:import> <c:import>
ReadcontentfromarbitraryURLs
Insertintopage
Storeinvariable
Ormakeaccessibleviaareader
Unlike<jsp:include>,notrestrictedtoownsystem
<c:redirect> <c:redirect>
RedirectsresponsetospecifiedURL
<c:param>
EncodesarequestparameterandaddsittoaURL
EL and J STL
Pradeep LN,
www.clearsemantics.com
3.23
Import
<c:importvar="data"url="/data.xml"/>
<c:outvalue="${data}/>
<c:importurl="/data.xml"/>
<c:urlvalue="/track.jsp"var="trackingURL">
<c:paramname="trackingId"value="1234"/>
<c:paramname="reportType"value="summary"/>
</c:url>
<c:importurl="${trackingURL}"/>
FunctionsinJSTL
<fn:length> <fn:length>
Lengthofcollectionofstring
<fn:toUpperCase>,<fn:toLowerCase>
Changethecapitalizationofastring
<fn:substring>,<fn:substringBefore>,
<fn:substringAfter> g
Getasubsetofastring
<fn:trim>
Trimastring
EL and J STL
Pradeep LN,
www.clearsemantics.com
3.24
FunctionsinJSTL
<fn:replace>
Replacecharactersinastring Replacecharactersinastring
<fn:indexOf>,<fn:startsWith>,<fn:endsWith
contains>,
<fn:containsIgnoreCase>
Checkifastringcontainsanotherstring
<fn:split> <fn:join> <fn:split>,<fn:join>
Splitastringintoanarray,andjoinacollectionintoa
string

You might also like