24
EL and JSTL © Pradeep LN, www.clearsemantics.com 3.1 Agenda •Use of the expression language Understanding the basic syntax Referencing scoped variables Accessing bean properties, array elements, List elements, and Map entries Using expression language operators E l i i di i ll Evaluating expressions conditionally

el and jstl

Embed Size (px)

Citation preview

Page 1: el and jstl

EL and JSTL

© Pradeep LN, www.clearsemantics.com

3.1

Agenda•Use of the expression languagep g g•Understanding the basic syntax•Referencing scoped variables•Accessing bean properties, array elements, List elements, and Map entries

•Using expression language operatorsE l i   i   di i llEvaluating expressions conditionally

Page 2: el and jstl

EL and JSTL

© Pradeep LN, www.clearsemantics.com

3.2

presenting the results in the JSP page.jsp useBean and jsp getPropert–jsp:useBean and jsp:getProperty

•Clumsy and verbose •Cannot access bean subproperties

– JSP scripting elements •Result in hard‐to‐maintain code  

presenting the results in the JSP page using EL.– More concise access – Ability to access subproperties– Simple syntax accessible to Web developers

ExampleIn jsp <jsp:useBean id="someName"  type="somePackage.someClass"

scope="request, session, or application"/><jsp:getProperty name="someName“ property="someProperty"/>

To:${someName.someProperty}

Page 3: el and jstl

EL and JSTL

© Pradeep LN, www.clearsemantics.com

3.3

Advantages of theExpression 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 ${companypresident firstName}  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  is interchangeable with the bracket notation for collections.

Succinct access to request parameters, cookies, and other request d t  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.

Page 4: el and jstl

EL and JSTL

© Pradeep LN, www.clearsemantics.com

3.4

EL syntax${expression}

Th  EL  l t      i   di  t t   i  JSP t   tt ib t   id d th t – These EL elements can appear in ordinary text or in JSP tag attributes, provided that those attributes permit regular  JSP expressions. For example:

<UL> <LI>Name: ${expression1} <LI>Address: ${expression2}

</UL> 

<jsp:include page="${expression3}" />

•The EL in tag attributes– You can use multiple expressions (possibly intermixed with static text) and the results are coerced to strings and  concatenated. For example:

<jsp:include page="${expr1}blah${expr2}" />

Accessing Scoped Variables

${varName}– Means to search thePageContext, theHttpServletRequest, the HttpSession, and the ServletContext, in that order, and output the object with that attribute name.

Equivalent forms${name}

<%= pageContext.findAttribute("name") %><jsp:useBean id="name“ type="somePackage.SomeClass“ scope="...">

<%= name %>

Page 5: el and jstl

EL and JSTL

© Pradeep LN, www.clearsemantics.com

3.5

Accessing Scoped Variablespublic class ScopedVars extends HttpServlet {public void doGet(HttpServletRequest request HttpServletResponsepublic void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException {

request.setAttribute("attribute1", "First Value");HttpSession session = request.getSession();session.setAttribute("attribute2", "Second Value");ServletContext application = getServletContext();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");

RequestDispatcher rd =request.getRequestDispatcher("scopedvars.jsp");rd.forward(request, response);}}

scopedvars.jsp<TABLE BORDER=5 ALIGN="CENTER"><TR><TH CLASS="TITLE">Accessing Scoped Variables</TABLE></TABLE><P><UL>

<LI><B>attribute1:</B> ${attribute1}<LI><B>attribute2:</B> ${attribute2}<LI><B>attribute3:</B> ${attribute3}<LI><B>Source of "repeated" attribute:</B> ${repeated}

</UL></BODY></HTML>

Page 6: el and jstl

EL and JSTL

© Pradeep LN, www.clearsemantics.com

3.6

Accessing Bean Properties${varName.propertyName}${varName.propertyName}– Means to find scoped variable of given name and output the specified bean property

Example:<body>Hello + ${customer.firstName}

</body>

Accessing Bean Properties(Contd..)${customer.firstName}

Equivalent forms<%@ page import=“com.NameBean”%><%NameBean person(NameBean)pageContext.findAttribute(“customer”);%>

<%= person.getFirstName() %>

OrOr <jsp:useBean id=“customer“ type=“com.NameBean”scope=“request, session, or application” />

<jsp:getProperty name=“customer” property=“firstName”/>

Page 7: el and jstl

EL and JSTL

© Pradeep LN, www.clearsemantics.com

3.7

Example: Accessing Bean Properties

public class BeanProperties extends HttpServlet {public void doGet(HttpServletRequest request HttpServletResponse response)public void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException {

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 tDi t h di t h t tR tDi t h ("bRequestDispatcher dispatcher = request.getRequestDispatcher("bean-properties.jsp");

dispatcher.forward(request, response);}}

Example: Accessing Bean Propertiespublic class EmployeeBean {private NameBean name;private CompanyBean company; public EmployeeBean(NameBean name, CompanyBean company) {p p y ( , p y p y)

setName(name);setCompany(company);

}public NameBean getName(){ return(name); }public void setName(NameBean newName) {name = newName;}public CompanyBean getCompany() { return(company); }public void setCompany(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;}…..

Page 8: el and jstl

EL and JSTL

© Pradeep LN, www.clearsemantics.com

3.8

Example: Accessing Bean Properties<!DOCTYPE …>…

UL<UL><LI><B>First Name:</B>

${employee.name.firstName}<LI><B>Last Name:</B>

${employee.name.lastName}<LI><B>Company Name:</B>

${employee.company.companyName}                 <LI><B>Company Business:</B><LI><B>Company Business:</B>

${employee.company.business}</UL>

</BODY></HTML>

Accessing Collections

${attributeName[entryName]}{ [ y ]}– Array. Equivalent to

theArray[index]– List. Equivalent to

theList.get(index)– Map. Equivalent to

h M (k N )theMap.get(keyName)• Equivalent forms (for HashMap)– ${stateCapitals["maryland"]}– ${stateCapitals.maryland}

Page 9: el and jstl

EL and JSTL

© Pradeep LN, www.clearsemantics.com

3.9

Example: Accessing Collections

public class Collections extends HttpServlet {public void doGet(HttpServletRequest request,HttpServletResponse response)p ( p q q , p p p )

throws ServletException, IOException {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");

request.setAttribute("first", firstNames);request.setAttribute("last", lastNames);request.setAttribute("company", companyNames);

RequestDispatcher dispatcher =request.getRequestDispatcher("/el/collections.jsp");dispatcher.forward(request, response);}}

Example: Accessing Collections<!DOCTYPE …>…<BODY><TABLE BORDER=5 ALIGN="CENTER"><TR><TH CLASS="TITLE">Accessing Collections</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>

Page 10: el and jstl

EL and JSTL

© Pradeep LN, www.clearsemantics.com

3.10

Implicit objects

Example: Implicit Objects<!DOCTYPE …><P>

<UL><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>/

Page 11: el and jstl

EL and JSTL

© Pradeep LN, www.clearsemantics.com

3.11

Expression Language Operators

Arithmetic– + ‐ * / div % modRelational– == eq != ne < lt > gt <= le >= geLogical– && and || or ! NotEmptyEmpty– Empty– True for null, empty string, empty array, empty list,

empty map. False otherwise.

Example: Operators<TABLE BORDER=1 ALIGN="CENTER"><TR><TH CLASS "COLORED" COLSPAN 2>Arithmetic Operators<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}<TR ALIGN="CENTER"><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>\${3%2}<TD>${3%2}<TD>\${3/4 == 0.75}<TD>${3/4 == 0.75}

Page 12: el and jstl

EL and JSTL

© Pradeep LN, www.clearsemantics.com

3.12

Example: Operators (Result)

Evaluating Expressions Conditionally

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

Page 13: el and jstl

EL and JSTL

© Pradeep LN, www.clearsemantics.com

3.13

Example:Conditional Expressionspublic class Conditionals extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {

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);

RequestDispatcher dispatcher =request.getRequestDispatcher (“/conditionals.jsp");dispatcher.forward(request, response);} }

public class SalesBean {private double q1, q2, q3, q4;public SalesBean(double q1Sales,double q2Sales,double q3Sales,double q4Sales) {q1 = q1Sales; q2 = q2Sales;q3 = q3Sales; q4 = q4Sales;}

public double getQ1() { return(q1); }public double getQ2() { return(q2); }public double getQ3() { return(q3); }public double getQ4() { return(q4); }public double getTotal() {return(q1 + q2 + q3 + q4); }

Example: Conditional Expressions 

<TABLE BORDER=1 ALIGN="CENTER"><TR><TH><TR><TH><TH CLASS="COLORED">Apples<TH CLASS="COLORED">Oranges<TR><TH CLASS="COLORED">First Quarter

<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}

…<TR><TH CLASS="COLORED">Total

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

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

</TABLE>…

Page 14: el and jstl

EL and JSTL

© Pradeep LN, www.clearsemantics.com

3.14

Example: Conditional Expressions (Result)

Page 15: el and jstl

EL and JSTL

© Pradeep LN, www.clearsemantics.com

3.15

JSTL (JSP Standard Tag Libraries) is a collection of JSP custom tags developed by Java 

What Is JSTL?

collection of JSP custom tags developed by Java Community Process, 

Need for JSTLSimplify JSP page authoringSimplify JSP page authoringProvide a standard library available on any JSP 1.2 containerMake dynamic web programming more accessible to non‐Java programmers

Page 16: el and jstl

EL and JSTL

© Pradeep LN, www.clearsemantics.com

3.16

Tag libraries: 

Multiple Tag LibrariesMultiple Tag LibrariesCore (c) XML (x)Formatting (fmt)SQL (sql)

Most tags can create Scoped Variablesg pAll Tags Support Tag Body

JSTL Tag libraries: Core ( c )Core ( c )‐<%@ taglib  uri="http://java.sun.com/jstl/core” prefix="c" %>

– Writing, creating scoped variables, conditionallogic, looping, URLs (import, redirect)

• Formatting ( fmt )<%@ taglib uri="http://java.sun.com/jstl/fmt" prefix="fmt" %>  

Internationali ation and locali ationInternationalization and localizationFormatting and parsing number

Page 17: el and jstl

EL and JSTL

© Pradeep LN, www.clearsemantics.com

3.17

JSTL Tag libraries: XML tags ( x )XML tags ( x )

<%@ taglib uri="http://java.sun.com/jstl/xml”prefix="x" %>

XML parsing, fragment selection, flow control(logic), transforming

Database tags ( sql )Limited use for non‐trivial appsDefault data source impl does not support connection pooling

Core Tag Library<c:out>To evaluate an expression and include theexpression’s output in the page

<c:out value="${p.value}“ default=“No value for parameter” />

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

<html><body>

<c:out value="Hello world!"/></body>

</html>

Page 18: el and jstl

EL and JSTL

© Pradeep LN, www.clearsemantics.com

3.18

Core Tag Library<c:set>create ormodify scoped variable

<c:set var=“Name” value=“${person.firstName}” />

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

<html><body><c:set var="customerID“ value=“1234"    scope="session”/><c:out value="${customerID}/>

</body></html>

Core Tag Library<c:remove>

d bl‐ removes a scoped variable‐ Scope is optional, but the attribute will be removed from all scopes if scope is not specified

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

<html><body><c:remove var=“customerID” scope=“session” />

</body></html>

Page 19: el and jstl

EL and JSTL

© Pradeep LN, www.clearsemantics.com

3.19

Core Tag Library<c:catch.> 

ff h dl h b ddeffective way to handle exceptions without embedding Java code in your pages

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

<html><body><c:catch><!‐‐ JSTL tags below which could  throw  an exception‐‐>

</c:catch></body></html>

<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 )throw newNullPointerException(); %>

</c:catch><c:choose><c:when test="${signalException != null}">Exception occurs.</c:when><c:otherwise> No Exception. </c:otherwise></c:choose>%> </body></html>

Page 20: el and jstl

EL and JSTL

© Pradeep LN, www.clearsemantics.com

3.20

Core Tag Library ‐ Conditionals<c:if> 

h l ' l h bThe Boolean expression's value in the test attribute is evaluated

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

<html><body><body><c:if test="${status.totalVisits == 1000000}" var="visits“>

You are the millionth visitor to our site!  Congratulations!</c:if>

</body></html>

Core Tag Library ‐ Conditionals<c:choose> 

l k f l f llike an if/else if/else statementor a switch statement without fall‐through

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

<html><body>

<c:choose><c:when test="${item.type == 'book'}“></c:when> <c:when test="${item.type == 'electronics'}“></c:when><c:when test="${item.type == 'toy'}“></c:when><c:otherwise></c:otherwise></c:choose></body></html>

Page 21: el and jstl

EL and JSTL

© Pradeep LN, www.clearsemantics.com

3.21

Core Tag Library ‐ Looping<c:foreach> 

h l bliterate over the elements in an iterable: an array, Collection, Map, ResultSet or a comma‐separated Strings

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

<html><body><c:forEach var="item" items="${arrayOfItems}“ ><c:out value = “${item.itemName}” /><c:out value = “${item.price}”/>

</c:forEach></body></html>

Core Tag Library ‐ url< c:url> 

ll h k d bl dAllows URL rewriting when cookies are disabled

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

<html><body><body><c:url value="http://pratian.com”  " var="myUrl" >     </c:url>

</body></html>

Page 22: el and jstl

EL and JSTL

© Pradeep LN, www.clearsemantics.com

3.22

To Include Content  in JSPInclude directive

Static (translation time)Include directive

<%@ include file=“Header.html” %>

jsp:include <jsp:include page=“Header.jsp” />

Dynamic (request time)

j p p g j p

To Include Content  using JSTL<c:import><c:import>

Read content from arbitrary URLsInsert into pageStore in variableOr make accessible via a readerUnlike <jsp:include>, not restricted to own system

<c:redirect><c:redirect>Redirects response to specified URL

<c:param>Encodes a request parameter and adds it to a URL

Page 23: el and jstl

EL and JSTL

© Pradeep LN, www.clearsemantics.com

3.23

Import<c:import var="data" url="/data.xml"/><c:out value="${data}/>

<c:import url="/data.xml"/>

<c:url value="/track.jsp" var="trackingURL">  <c:param name="trackingId" value="1234"/> <c:param name="reportType" value="summary"/>

</c:url><c:import url="${trackingURL}"/> 

Functions in JSTL<fn:length> <fn:length> 

Length of collection of string<fn:toUpperCase>, <fn:toLowerCase>Change the capitalization of a string

<fn:substring>, <fn:substringBefore>, <fn:substringAfter>g

Get a subset of a string<fn:trim> Trim a string

Page 24: el and jstl

EL and JSTL

© Pradeep LN, www.clearsemantics.com

3.24

Functions in JSTL<fn:replace>

Replace characters in a stringReplace characters in a string<fn:indexOf>, <fn:startsWith>, <fn:endsWith contains>,<fn:containsIgnoreCase> 

Check if a string contains another string<fn:split>  <fn:join> <fn:split>, <fn:join> Split a string into an array,and join a collection into a string