Building JSP Pages Using The Expression Language (EL)
Building JSP Pages Using The Expression Language (EL)
Durga
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
173 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
ADV. JAVA With SCWCD/ OCWCD Material By Mr. Durga
Agenda:
1) Introduction
2) EL Implicit Objects :
● pageScope, requestScope, sessionScope, applicationScope
● param & paramValues
● header & headerValues
● initParam
● cookie
● pageContext
● handling errors
3) EL Operators :
● property access operator ( . )
● collection access operator []
● Arithmetic operators ( +, -, *, /, % )
● Relational operators ( lt, gt, eq, ne ) OR ( <, >, <=, >=, ==, =!)
● Logical operators ( and, or, not )
● conditional operator ( ?: )
● empty operator ( empty )
● EL operator presidency
● EL reserved words
● EL Vs null
4) EL Functions :
● Write a java class
● Write a TLD file : (tag library descriptor file)
● Write a taglib directive
● Write EL function call
● Work Flow : (in EL function application)
Introduction
E-L introduced in Jsp 2.0v , the main objective of EL is to eliminate java code from the jsp.
In general we can use EL with JSTL and custom tags for complete elimination of java code from
the jsp.
EL expressions are always with in { } and prefixed with $ (dollar) sign
syntax:
${leftVatiable.rightVariable}
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
174 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
ADV. JAVA With SCWCD/ OCWCD Material By Mr. Durga
The leftVariable can be any EL implicit objects/attributes stored in some scopes (page scope,
request scope, session scope, application scope)
To print the value of request parameter "user" in jsp, write the code ?
<%= request.getparameter("user") %>
// is equivalent code
${param.user}
To print the value of session scoped attribute "x" in jsp ?
// is equivalent code
${sessionScope.x}
${x}
<%!
int x = 10;
%>
The value of x is : ${x}
output :
The value of x is : //BlankSpace
Ex 2:
output :
The value of x is : 10
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
175 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
ADV. JAVA With SCWCD/ OCWCD Material By Mr. Durga
1. pageScope
2. requestScope
----> map objects to retrieve scoped attributes
3. sessionScope
4. applicationScope
5. param
----> map objects to retrieve form parameters
6. paramValues
7. header
----> map objects to retrieve request headers
8. headerValues
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
176 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
ADV. JAVA With SCWCD/ OCWCD Material By Mr. Durga
${sessionScope.x}
Ex : To print the value of request scoped attribute "x"
${requestScope.x}
Ex :
${sessionScope.x}
It prints the value of session scoped attribute "x" , in sessionScope if there is no such attribute then
we will get BlankSpace
Ex :
${x}
jsp engine first checks in pageScope for attribute "x" if it is available then it prints the value, then it's
not available it will check in requestScope followed by sessionScope and applicationScope, it simply
act as pageContext.findAttribute(x);
scopes.jsp
Note : ${leftVariable.rightVariable}
If leftVariable is a map then rightVariable should be "key", If the specified key is not available
then we will get BlankSpace as a output.
If leftVariable is a bean then rightVariable should be "property", If the specified property is
not available then we will get "PropertyNotFoundException".
${person.empId}
// here person attribute stored in some scope
In Servlet code :
package foo;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
p.setDog(d);
request.setAttribute("person", p);
request.setAttribute("arun", "SCWCD");
RequestDispatcher rd = request.getRequestDispatcher("demo.jsp");
rd.forward(request, response);
}
}
in Jsp code :
${requestScope.arun}
${requestScope.person.dog.name}
use requestScope implicit object to get request scoped attributes but not request parameters.
If we want request properties then we should go for pageContext EL implicit object.
${param.x} // it prints the value of form parameter x, if the specified parameter is not available then
we will get BlankSpace
If parameter associated with multiple values then we will get first value.
param :
Map
String String
uname ashok
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
178 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
ADV. JAVA With SCWCD/ OCWCD Material By Mr. Durga
course scwcd
place hyd
paramValues :
Map
String String[]
place {hyd}
${paramValues.uname}
// String[] will be returns on that Object class toString() is called.
Note : EL handles null and ArrayIndexOutOfBoundException very nicely and prints BlankSpace.
form.html
formParam.jsp
<%@page isELIgnored="false"%>
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
179 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
ADV. JAVA With SCWCD/ OCWCD Material By Mr. Durga
These are exactly similar to param and paramValues except that these are retrieving request headers.
If the specified request header is not available you will get BlankSpace as a output.
header.jsp
<%@page isELIgnored="false"%>
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
180 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
ADV. JAVA With SCWCD/ OCWCD Material By Mr. Durga
initParam :
By using initParam implicit object we can access ServletContext parameters but not servlet
initialization parameters.
${initParam.user} // it prints the value associated associated with context parameter user.
${initParam.x} //BlankSpace
initParam.jsp
web.xml
<context-param>
<param-name>name</param-name>
<param-value>Ashok</param-value>
</context-param>
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
181 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
ADV. JAVA With SCWCD/ OCWCD Material By Mr. Durga
<context-param>
<param-name>mail</param-name>
<param-value>admin@jobs4times.com</param-value>
</context-param>
<context-param>
<param-name>age</param-name>
<param-value>2022</param-value>
</context-param>
<context-param>
<param-name>x</param-name>
<param-value>12345</param-value>
</context-param>
<context-param>
<param-name>y</param-name>
<param-value>54321</param-value>
</context-param>
<%
Cookie[] c=request.getCookies();
for(int i=0;i<c.length;i++) {
if(c[i].getName().equals("userName")) {
out.println(c[i].getValue());
}
}
%>
(OR)
cookie :
By using cookie implicit object we can retrieve cookies associated with the request
cookie :
Map
String String
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
182 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
ADV. JAVA With SCWCD/ OCWCD Material By Mr. Durga
JSESSSIONID 1234
c1 SCJP
cookie.jsp
<%
Cookie c1=new Cookie("c1","SCJP");
Cookie c2=new Cookie("c2","SCWCD");
response.addCookie(c1);
response.addCookie(c2);
%>
pageContext :
This is only one EL implicit object which matches with jsp implicit object.
This is only one EL implicit object which is a non-map object by using this implicit object we
can bring all jsp implicit objects into EL.
${pageContext.request.method} <br/>
${pageContext.session.id} <br/>
${pageContext.request.Cookies[0]} <br/>
${course} <br/>
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
183 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
ADV. JAVA With SCWCD/ OCWCD Material By Mr. Durga
${request.method} <br/>
${session.id} <br/>
handling errors :
There is an exception and it was not caught then in this case the request will be forwarded
along with exception to the error page URL, here the error page is specified errorPage
attribute of page directive and by specified URL.
This is so simple because the error page itself is identified by using the implicit object
exception, more over in addition to exception object an error page also has the following
request attributes available.
javax.servlet.error.status-code
javax.servlet.error.request-URI
javax.servlet.error.servlet-name
When ever we use the pageContext.getErrorData() method, it is possible to get an instance
of javax.servlet.jsp.Error-Data class
This will provide to find a simple way to access the above attributes. (status-code, request-
URI, servlet-name)
index.jsp
<%@page isELIgnored="false" %>
error.jsp
<%@page isErrorPage="false"%>
EL Operators :
EL contains it's own specific operators the following is list of all possible operators
6. conditional operator ( ?: )
7. empty operator ( empty )
If the expression has a variable followed by . (dot) , the left variable must be a map or bean.
The thing to the right of the . (dot) must be a key or bean property.
The thing on the right must follow normal java naming rules for the identifies.
${person.name}
//javax.el.ELExpeption:ErrorParsing
When we use the . operator the thing on the left can be only a Map or Bean and thing on the right
must follow java naming rules for the identifies but with collection access operator, the thing on the
left can also be a List or Array that also meaning the thing on the right can be a number or any thing
that resolves to a number or an identifier that doesn't java naming rules.
Ex :
${musicMap[MusicTypes[0]]}
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
185 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
ADV. JAVA With SCWCD/ OCWCD Material By Mr. Durga
(OR)
${musicMap[MusicTypes["0"]]}
${musicMap[MusicTypes["zero"]]}
// It can't convert into int
Map Example :
${initParam['mail']}
${initParam['age']}
${initParam['name']}
${initParam[age]}
<%-- blank space --%>
Note : If we are not using code symbol then it is treated as attribute if the specified attribute is not
available then we will get blank space.
package foo;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
p.setDog(d);
request.setAttribute("person", p);
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
186 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
ADV. JAVA With SCWCD/ OCWCD Material By Mr. Durga
RequestDispatcher rd = request.getRequestDispatcher("view.jsp");
rd.forward(request, response);
}
view.jsp
${person['dog']['name']}
${person[dog][name]} //blankspace
List Example :
Servlet code :
package foo;
import java.io.IOException;
import java.util.ArrayList;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
request.setAttribute("x", list);
request.setAttribute("index", "2");
RequestDispatcher rd = request.getRequestDispatcher("view.jsp");
rd.forward(request, response);
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
187 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
ADV. JAVA With SCWCD/ OCWCD Material By Mr. Durga
}
view.jsp
Array Example :
servlet code :
package foo;
import java.io.IOException;
import java.util.HashMap;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
request.setAttribute("musicMap", musicMap);
String[] musicTypes = {"melody","DJ","fastBeat","slowBeat"};
request.setAttribute("musicType", musicTypes);
RequestDispatcher rd = request.getRequestDispatcher("view.jsp");
rd.forward(request, response);
}
}
view.jsp
${ musicMap[musicType[1]] }
${ musicMap["DJ"] }
note : first inner most brackets will be evaluated.
Ex 2 :
Example :
Person.java
package foo;
}
Dog.java
package foo;
package foo;
package foo;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
190 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
ADV. JAVA With SCWCD/ OCWCD Material By Mr. Durga
p.setName("SAI");
p.setDog(d);
d.setToys(new foo.Toy[]{t,t1,t2});
request.setAttribute("person", p);
RequestDispatcher rd = request.getRequestDispatcher("view.jsp");
rd.forward(request, response);
}
view.jsp
<%@ page isELIgnored="false"%>
Note : Where ever property access operator is required there we can use collection access operator
but where ever collection access operator is required may not be use property access operator.
EL doesn't support operator overloading and + operator always meant for Arithmetic addition but not
for String Concatenation.
+ operator :
<%@ page isELIgnored="false"%>
2+3= ${2+3}
"2"+3= ${"2"+3}
"2"+'3'= ${"2"+'3'}
abc+'3'= ${abc+'3'}
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
191 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
ADV. JAVA With SCWCD/ OCWCD Material By Mr. Durga
"abc"+'3'= ${"abc"+'3'}
// java.lang.NullPointerException:For input string: "abc"
""+3= ${""+'3'}
// java.lang.NullPointerException:For input string: ""
null+'3'= ${null+'3'}
- operator :
<%@ page isELIgnored="false"%>
2-3= ${2-3}
"2"-3= ${"2"-3}
"2"-'3'= ${"2"-'3'}
abc-'3'= ${abc-'3'}
"abc"-'3'= ${"abc"-'3'}
// java.lang.NullPointerException:For input string: "abc"
""-3= ${""-'3'}
// java.lang.NullPointerException:For input string: " "
null-'3'= ${null-'3'}
* operator, / operator : all rules are exactly similar to + operator except that division operator always
follows floating point Arithmetic.
syntax :
Ex :
${10/2} = 5.0
${10/0} = Infinity
${0/0} = NaN
% operator :
All rules are exactly similar to + operator here both integral and floating Arithmetics are possible.
syntax :
Ex :
${10%3} // 1
${10.0%0} //NaN
${""/'3'}
//java.lang.NumberFormatException: empty String
Note : In Arithmetic operator null evaluates Zero, the presidency of Arithmetic operators *, /, %, +, -.
package foo;
import java.io.IOException;
import java.util.ArrayList;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
String[] s = {"melody","DJ","fast","slow"};
request.setAttribute("musicList", s);
RequestDispatcher rd = request.getRequestDispatcher("view.jsp");
rd.forward(request, response);
}
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
193 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
ADV. JAVA With SCWCD/ OCWCD Material By Mr. Durga
view.jsp
<%@ page isELIgnored="false"%>
${musicList[numbers[0]]} <br/>
${musicList[numbers[1]+2]} <br/>
${musicList[numbers[numbers[0]]+1]} <br/>
${musicList[numbers["2"]]} <br/>
Relational operators :
< or lt
<= or le
> or gt
>= or ge
== or eq
=! or ne
Ex :
<%@ page isELIgnored="false"%>
Relational operators :
Logical operators :
&& or and
|| or or
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
194 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
ADV. JAVA With SCWCD/ OCWCD Material By Mr. Durga
! or not
Ex :
<%@ page isELIgnored="false"%>
empty operator :
syntax :
${empty obj}
returns true iff object doesn't exists/ an empty array/ object is an empty collection/ object as a empty
String in all other cases it returns false.
Ex :
In Servlet code :
package foo;
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
195 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
ADV. JAVA With SCWCD/ OCWCD Material By Mr. Durga
import java.io.IOException;
import java.util.ArrayList;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
int num = 2;
request.setAttribute("num", num);
RequestDispatcher rd = request.getRequestDispatcher("jspDemo.jsp");
rd.forward(request, response);
}
view.jsp
<%@ page isELIgnored="false"%>
EL operator presidency :
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
196 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
ADV. JAVA With SCWCD/ OCWCD Material By Mr. Durga
1. unary (! , empty )
2. Arithmetic ( *, /, %, +, - )
3. Relational ( <, >, <=, >=, ==, =!)
4. Logical ( &&, || )
5. conditional operator ( ?: )
EL reserved words :
lt
true
gt
false instanceof
le div
and empty
ge mod
or null
ne
not
eq
EL Vs null :
1. EL behavior very nicely with null, in Arithmetic operator null is treated as a zero.
2. With String evaluation null is treated as empty String (" ")
3. With logical operators null is treated as false
4. In the case of empty operator null is treated as true
5. In the case of relational operator null is treated as false
Assume that there is no attribute named with "foo" but there is an attribute named with "bar" but
bar doesn't have any property or key name "foo"
${foo} // BlankSpace
${foo[bar]} // BlankSpace
${bar[foo]} // BlankSpace
${foo.bar} // BlankSpace
${7/foo} // Infinity
${7%foo} // java.lang.ArithmeticException
${true and false} // false
${true or false} // true
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
197 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
ADV. JAVA With SCWCD/ OCWCD Material By Mr. Durga
EL Functions :
1. Any java class can act as a repository for EL functions , the only requirement of the method
that act as a functions it should be public and static.
2. The method can take parameter also, there are no restriction on return type even void return
type is also allowed.
TLD file is a xml file which provides mapping between java class (where functionality is available) and
jsp (where functionality is required)
We can configure EL function by using function tag in TLD file , it contains the following 4 steps :
We have to declare taglib directive in the jsp to provide location of the TLD file
<%@taglib prefix="mime" uri="www.jobs4times.com" %>
${mime.getBalance(435678)}
demo.jsp
<%@ page isELIgnored="false"%>
<%@taglib prefix="mime" uri="DiceFunctions"%>
${mime:rollIt()} <br/>
${mime:rollIt()} <br/>
${mime:rollIt()} <br/>
DiceRoller.java
package foo;
public DiceRoller() {
System.out.println("DiceRoller");
}
public static int rollDice() {
return (int) (Math.random() *6+1);
}
myTld.tld
<?xml version="1.0" encoding="UTF-8"?>
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
199 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
ADV. JAVA With SCWCD/ OCWCD Material By Mr. Durga
1. When ever jsp engine encounters EL function call in jsp first it identifies the prefix and check
for corresponding taglib directive with matched prefix.
2. From the taglib directive jsp engine identifies uri and checks for corresponding TLD file with
matched uri.
3. From the TLD file jsp engine identifies the corresponding java class and method.
4. Jsp engine execute that method and returns its result to jsp.
Note :
The common thing between EL function call and taglib directive is "prefix".
The common thing between taglib directive and TLD file is "uri".
The common thing between TLD file and java class is "class name" and "method" .
Write a program to invoke Math class sqrt() as a EL function call with name m1
index.jsp
<%@ page isELIgnored="false"%>
<%@taglib prefix="mime" uri="MathFunctions"%>
mathFunction.tld
<taglib version="2.1" >
<tlib-version>1.0</tlib-version>
<uri>MathFunctions</uri>
<functions>
<name>m1</name>
<function-class>java.lang.Math</function-class>
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
200 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
ADV. JAVA With SCWCD/ OCWCD Material By Mr. Durga
<function-signature>double sqrt(double)</function-signature>
</functions>
</taglib>
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
201 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
ADV. JAVA With SCWCD/ OCWCD Material By Mr. Durga
nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
202 040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com