Nearby lessons

27 of 30

JSP Examples - Expression Language (EL)

📌 What You Will Learn
  • Read request data with EL instead of scriptlets
  • Master EL operators and precedence
  • Declare and invoke custom EL functions

EL demo programs: implicit objects (param, header, cookie, initParam, scopes), operators, precedence, the empty operator, EL versus null, and custom EL functions with TLD declarations.

EL Implicit Objects

(But not Servlet Initialization Parameters)

  • pageScope,requestScope,sessionScope and applicationScope

We can use these implicit objects to retrieve attributes of a particular scope

pageScopepageContext.getAttribute()

requestScope request.getAttribute()

sessionScope session.getAttribute()

applicationScope application.getAttribute()

Eg1:

To get the value of session scoped attribute x

${sessionScope.x}

Eg2:

To get the value of request scoped attribute x

${requestScope.x}

Eg3:

${x}

JSP Engine first checks in page scope for the attribute "x". If it is available then JSP Engine prints

its value. If it is not available then JSP engine will search in request scope followed by session

scope and application scope. It is exactly same as findAttribute()

test.jsp:

Example01
JCode Cell
1 
2pageScope Map of Scoped Attributes
3requestScope
4sessionScope
5applicationScope
6param Map of Request Parameters
7paramValues
8header Map of Request Headers
9headerValues
10cookie Map of Cookies
11initParam
12pageContext A Map of Context Initialization Parameters
13

EL Implicit Objects

Output:

Pavan

ravi

sunny

anushka

Pavan

  • param and paramValues

We can use these implicit objects to retrieve request form parameters.

param getParameter()

paramValues getParameterValues()

${param.x}

It prints the value of form parameter x

If the parameter associated with multiple values then we will get only first value.

If the specified parameter not available then we will get blank space

${paramValues.x}

Internally it returns String[] which contains all values associated x. as we are printing that String[],

internally toString() method will be called, which prints result in the following form

[Ljava.lang.String;@1270b73

${paramValues.x[0]} It prints first value of x

${paramValues.x[1]} It prints second value of x

${paramValues.x[100]} prints blank space as EL suppresses ArrayIndexOutOfBoundsException

Example02
JCode Cell
1 
2<%
3pageContext.setAttribute("p","Pavan");
4pageContext.setAttribute("p","ravi",2);
5pageContext.setAttribute("p","sunny",3);
6pageContext.setAttribute("p","anushka",4);
7%>
8<h1>${pageScope.p}<br>
9${requestScope.p}<br>
10${sessionScope.p}<br>
11${applicationScope.p}<br>
12${p}<br>
13

Demo Program

  • header and headerValues:

These are exactly same as param and paramValues except that these are for retrieving request

headers.

header request.getHeader()

headerValues request.getHeaders()

Eg:

<h1>${header.accept}<br>

<h1>${header.host}<br>

<h1>${headerValues.host[0]}

  • cookie implicit object :

By using this implicit object we can get cookies associated with the request.

cookie request.getCookies()

<h1>${cookie.JSESSIONID.name}<br>

${cookie.JSESSIONID.value}

  • initParam implicit object:

We can use initParam implicit object to access context parameters declared in web.xml

initParam context.getInitParameter()

Example03
JCode Cell
1 
2<form action="el3.jsp" >
3Enter name: <input type=text name=uname><br>
4Enter EmpId:<input type=text name=eid><br>
5Enter Food1:<input type=text name=food><br>
6Enter Food2:<input type=text name=food><br>
7<input type=submit>
8</form>el3.jsp:
9<h1>
10Name:${param.uname}<br>
11Emp Id: ${param.eid}<br>
12Food: ${param.food}<br>
13Food[]:${paramValues.food}<br>
14Food1: ${paramValues.food[0]}<br>
15Food2: ${paramValues.food[1]}<br>
16Food100: ${paramValues.food[100]}<br>
17</h1>
18

Demo Program

Note:

If the specified initParameter is not available then we will get blank space b'z EL suppresses null

  • pageContext implicit object:

This is the only common implicit object between JSP and EL.

This is the only EL implicit object which is a non-map object.

By using this implicit object we can access all other JSP implicit objects in EL.

Eg:invalid
${request.method}valid
${pageContext.request.method}invalid
${session.id}valid

${pageContext.session.id}

In EL, request and session implicit objects are not available.

Note: El handles null and ArrayIndexOutOfBoundsException very nicely and prints blank space

EL Operators

EL contains its own specific operators. The following is the list of all possible operators.

Example04
JCode Cell
1 
2<web-app>
3<context-param>
4<param-name>user</param-name>
5<param-value>scott</param-value>
6</context-param>
7<context-param>
8<param-name>pwd</param-name>
9<param-value>tiger</param-value>
10</context-param>
11</web-app>el6.jsp:
12<h1>User: ${initParam.user}<br>
13<h1>Pwd: ${initParam.pwd}<br>
14<h1>Mail Id: ${initParam.mailId}<br>
15

Demo Program

Syntax: ${leftvariable.rightvariable}

Left Variable Map OR Bean

Right Variable Map Key OR Property

Should be Valid Java Identifier

Eg:

${customer.name}valid

${pageContext.request.method} valid

${initParam.user}valid
${customer.1234}invalid
Example05
JCode Cell
1 
2Property Access operator(.)
3Collection Access Operator( [] )
4Arithmetic Operators
5Relational Operators
6Logical Operators
7Property Access operator(.)
8

Demo Program

Syntax: ${leftvariable[rightvariable]}

map keyShould be enclosed either in Single OR Double Quotes

bean property

array index

list index Quotes are Optional

key or property should be enclosed in either single quotes or double quotes. For index quotes are

optional.

Case-1:working with Map:

${initParam["user"]}

${initParam['user']}

${initParam[user]} blank space

If we are not keeping quotes EL assumes that the key is an attribute stored in some scope. If that

attribute is not available then we will get blank space as output.

Q. Which of the following is the valid way of retrieving request header "accept" value?

Example06
JCode Cell
1 
2Collection access operator( [] ):
3

Demo Program

Case-2: working with Bean:

${customer['name']}

${customer["name"]}

${customer[name]} blank space as o/p

case-3: Working with arrays:

Example07
JCode Cell
1 
2${header.accept}
3${header[accept]} blank space as output
4${header["accept"]}
5${header['accept']}
6

Demo Program

Case-4: working with List objects:

Example08
JCode Cell
1 
2<%
3String[] s ={"AAA","BB","CCCC"};
4pageContext.setAttribute("s",s);
5%>
6<h1>
7${s[0]}
8${s["1"]}
9${s['2']}
10${s[3]}==>blank space
11

Demo Program

Note: where ever property access operator is required there we can use collection access

operator. But where ever collection access operator is required we may not use property access

operator

3.Arithmetic operators:

1.+ operator:

EL does not support overloading and hence there is no string concatenation operator. "+" always

acts as addition operator

Eg:

${2+3} 5

${"abc"+3}RE: NumberFormatException

${abc+3} 3

${""+3} 3

${null+3} 3

Note:

  • In Arithmetic operators null is treated as "0"
  • Empty String is also treated as "0"
  • - operator:

All rules are exactly same as + operator

${10-3} 7

${"10"-3} 7

${"abc"-3} RE:NFE

${abc-3} -3

  • * operator:

All rules are exactly same as + operator

${10 *3} 30

Example09
JCode Cell
1 
2<%@ page import="java.util.*" %>
3<%
4ArrayList l = new ArrayList();
5l.add("AAA");
6l.add("BBB");
7l.add("CCC");
8l.add("DDD");
9pageContext.setAttribute("list",l);
10pageContext.setAttribute("index",3);
11%>
12<h1>
13${list[0]}<br/>
14${list["1"]}<br/>
15${list['2']}<br/>
16${list[index]}
17

Demo Program

All rules are exactly same as + operator except that division operator always follows floating point

arithmetic

${10 / 2} 5.0

${10 div 2} 5.0

${10 / 0} Infinity

${0 / 0} NaN

Example10
JCode Cell
1 
2/ operator or (div)
3

Demo Program

In the case of mod operator both floating point and integral arithmetic are possible.

${10%0} ArithmeticException

${10%3} 1

Relational operators:

> or gt

< or lt

== or eq

>= or ge

<= or le

!= or ne

${10>3} true

${abcd==abc} true

Example11
JCode Cell
1 
2% operator (or) mod operator:
3

EL operator precedence

3.Relational

4.logical operators

5.conditional operator

Example12
JCode Cell
1 
2unary operators (!, empty)
3*,/,%,+,-
4

EL versus null

  • Writing tag library descriptor file(tld file):

For EL functions, tld file provides mapping between java class (where functionality is available) &

JSP (where functionality is required).

We can configure EL function by using <function> tag in the tld file.

<function> tag contains the following 4 child tags

Example13
JCode Cell
1 
2package pack1;
3public class DiceRoller
4{
5public static int rollDice()
6{
7return (int)((Math.random()*6)+1);
8}
9}
10

EL versus null

By using this name only we can call EL functionality in the JSP.

This name need not be original name of the method

Example14
JCode Cell
1 
2<description>
3<name>
4

EL versus null

The fully qualified name of java class where EL function is defined

Example15
JCode Cell
1 
2<function-class>
3

EL versus null

The signature of EL function which is defined in java class.

Here we have to provide return type, method-name & argument list

Eg: myfunctions.tld:

Example16
JCode Cell
1 
2<function-signature>
3

EL versus null

  • Write taglib directive:

we can write taglib directive to make EL Functions available to the JSP

<%@ taglib prefix="mime" uri="DiceFunctions" %>

  • Write EL function call:

${ mime:rollIt()}

Example17
JCode Cell
1 
2<taglib version="2.1" >
3<tlib-version>1.2</tlib-version>
4<uri>DiceFunctions</uri>
5 
6<function>
7<name>rollIt</name>
8<function-class>pack1.DiceRoller</function-class>
9<function-signature>int rollDice()</function-signature>
10</function>
11 
12</taglib>
13

Demo Program

Example18
JCode Cell
1 
2<%@ taglib prefix="mine" uri="DiceFunctions" %>
3<h1>Your 3-digit Lucky number is:
4${mine:rollIt()}
5${mine:rollIt()}
6${mine:rollIt()}</h1>MyFunctions.tld
7<taglib version="2.1" >
8<tlib-version>1.2</tlib-version>
9<uri>DiceFunctions</uri>
10 
11<function>
12<name>rollIt</name>
13<function-class>pack1.DiceRoller</function-class>
14<function-signature>int rollDice()</function-signature>
15</function>
16 
17</taglib>
18

DiceRoller.java

elApp1

|-test.jsp

|-WEB-INF

|-MyFunctions.tld

|-classes

|-pack1

|-DiceRoller.class

Execution Flow of EL Function

EL Function call in JSP

Taglib Directive with

Matched Prefix

TLD File with

Matched URI

Java Class with Matched

function-class & Signature

  • Whenever JSP engine encounters EL Function call with Prefix and EL Function Name, then it

checks for corresponding taglib directive with matched prefix.

  • From taglib directive JSP engine identifies uri and checks for tld file with matched uri.
  • From the TLD file JSP engine identified java class and method signature.JSP engine will check for

the matched java class and method signature.

  • JSP Engine executes that method and return its results to JSP.

Demo Program-2:

Write application to invoke Math class sqrt() method as EL Function call with method name m1().

public static double sqrt(double d)

test.jsp:

Example19
JCode Cell
1 
2package pack1;
3public class DiceRoller
4{
5public static int rollDice()
6{
7return (int)((Math.random()*6)+1);
8}
9}
10

DiceRoller.java

Example20
JCode Cell
1 
2<%@ taglib prefix="mine" uri="MathFunctions" %>
3 
4<h1>The Square Root of 4 is:${mine:m1(4)}<br>
5<h1>The Square Root of 36 is:${mine:m1(36)}<br>
6

MyTld.tld

|-test.jsp

|-WEB-INF

|-MyTld.tld

Example21
JCode Cell
1 
2<taglib version="2.1">
3<tlib-version>1.2</tlib-version>
4<uri>MathFunctions</uri>
5<function>
6<name>m1</name>
7<function-class>java.lang.Math</function-class>
8<function-signature>double sqrt(double)</function-signature>
9</function>
10</taglib>elApp2
11
📝 Key Takeaways
  • EL suppresses null output
  • EL functions must be declared in a TLD
  • empty covers both null and zero-length values