Back to: JSP Tutorials for Beginners and Professionals
Expression Language in JSP with Examples
In this article, I am going to discuss Expression Language in JSP with Examples. Please read our previous article, where we discussed JSP Exception Handling with Examples. As part of this article, we are going to discuss the following pointers.
- What is Expression Language (EL) in JSP?
- Why we need Expression Language (EL) in JSP?
- JSP Syntax of Expression Language (EL)
- Implicit Objects in Expression Language (EL)
- EL param example
- EL sessionScope example
- EL cookie examples
- Operators in EL
- Precedence of Operators in EL
- Reserve words in EL
- Functions in JSP EL
- JSP EL Implicit Objects
- The pageContext Object
- The Scope Objects
- The param and param Values Objects
- header and header Values Objects
- Flow Control Statements:
- Decision-Making statements
- Loop Statements
What is Expression Language in JSP?
It has introduced in JSP 2.0 version. Expression Language is mainly used to eliminate java code from the JSP. In general, to eliminate java code and scripting elements from JSP pages, we have to use custom action which requires a lot of java code internally in order to implement simple programming like if, switch, for, and so on. To overcome the above problem, we have to use Expression Language syntax along with standard actions, custom actions, and JSTL tag library.
Syntax: ${expression}, expression is the value present which is evaluated at runtime and being sent to the output stream.
Example
To print the value of request parameter uname: We have to use java code before expression language to get a particular request parameter from the request object.
<% uname=request.getParameter(“uname”);%>
In this example, we are able to retrieve a particular request parameter without using java code by using expression language syntax. ${param.uname}
Why we need Expression Language in JSP?
- We can get request parameters
- We can get any scope attributes
- We can get values of bean objects stored in a scope
- We can get request header values.
- We can get context parameter values
- We can get cookie values
- We can get JSP implicit objects
- We can do arithmetic, relational, logical, and conditional operations
- We can call static methods of a class by using EL functions
Elements of Expression Language
To eliminate java code completely from JSP pages, by using the following expression language elements:
- EL operators
- EL implicit objects
- EL functions
Expression Language Operators in JSP
EL contains its own set of operators, the following is the list of available operators in EL:
Property access operators (.)
Syntax: ${leftvariable.rightvariable}
${param.uname},${pageContext.session}
Collection access Operators ([])
Syntax: ${left variable[right variable]}
Example
${initParam.mail}
${initParam[‘mail’]}
${initParam[“mail”]}
Example of Arrays
<%
String[] s={“CoreJava”,”Spring”, “Hibernate”,”WebServices”}
pageContext.setAttribute(“s”,s);
%>
${s[0]} -> CoreJava
${s[1]} -> Spring
${s[2]} -> Hibernate
${s[3]} -> WebServices
${s[100]} -> blankspace
Example for List:
<%@page isELIgnored=”false”%>
<%
Java.uil.ArrayList al=new java.util.ArrayList();
al.add(“student1”);
al.add(“student2”);
al.add(“student3”);
pageContext.setAttribute(‘list”,1,2);
%>
<h1>
${list[0]} -> student1
${list[“1”]} -> student2
${list[100]} -> blank space
Arithmetic Operator
EL does not support operator overloading hence ‘+’ operator always meant for arithmetic addition operator.
‘+’ operator
${2+3} -> 5
${“2″+”3”} -> 5
${“2″+’3′} -> 5
${abc+’3′} -> 3
${null+”3″} -> 3
${“abc”+”3”} -> Number Format Exception
${” “+”3”} -> Number Format Exception
‘-‘ operator
${a-b}
All rules is exactly same as ‘+’ operator
${10-3} -> 7
${“abc” – 3} -> Number Format Exception
‘*’ operator
${a*b}
All rules are exactly similar to “=” operator
${19*2} -> 38
‘/’ operator
${a/b} or ${a div b}
All rules are exactly same as “+” operator
${10/2} -> 5
${10/0} -> infinity
Division operators always follow floating-point arithmetic but not integral arithmetic.
Module Operator (% or mod)
All the rules are exactly same as ‘+’ operator and this operator can provide support for both integral and floating-point arithmetic.
${10%3} -> 1
${10%0} -> Arithmetic Exception
$(10.0/0) -> NaN (Not any Number)
Relational Operators
>or greater trhan
${2>1} -> true
<or lt
${3<4} -> true
== or eq
${abcd==abcd) -> true
${“abcd”==”abc”} -> true
!= or ne
>= or ge
<= or le
Logical Operators
and | &&
${true and false} -> false
Or | ||
${true or false} -> true
not | !
${not true} -> false
Conditional Operator
${(3<4) ? “yes” : “no”} -> yes
${(true==false) ? “Right” : “wrong”} -> wrong
Empty Operator
${empty object}
Returns true
- If object does not exist
- If objects is an empty array
- Object is an empty string
- Object is a collection
In all other cases it returns false.
${empty abcd} -> true
${empty “abcd”} -> false
${empty null} -> true
Note: JSP EL supports most of the arithmetic and logical operators supported by Java.
Precedence of Operators in Expression Language
[] .
()
-(unary) not ! empty
* / div % mod
+ – (binary)
< <= > >= lt le gtg e
== != eq ne
&& and
|| or
?:
Example
In this example, we are taking three variables (num1, num2, num3) where we are using the JSP operator “+” to add two variables (num1 and num2) and get the third variable(num3). Then we will check a condition whether the variable (num3) is not equal to 0 by using JSP operators (!=, >) and then we will take another variable (num4) by multiplying num1 and num2 and we get num4.
ELoperators.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>EL operators</title> </head> <body> <% int num1 = 100; int num2 = 500; int num3 = num1 + num2; if (num3 != 0 || num3 > 0) { int num4 = num1 * num2; out.println("Number 4 is " + num4); out.println("<br/>"); out.println("Number 3 is " + num3); } %> </body> </html>
Output
Reserve Words in Expression Language
Following are the reserve words in JSP Expression Language:
lt
le
gt
ge
eq
ne
true
false
and
or
not
instanceof
div
mod
empty
null
Implicit Objects in JSP Expression Language
We can use JSP implicit objects in scripting elements to reduce Java code inside the scripting elements. The power of EL is just because of these objects only. Similarly, JSP Expression Language has provided the following list of implicit objects to eliminate Java code from JSP pages:
- Page scope: It is used to access the attribute data with the values in the page scope. pageContext.getAttribute();
- request scope: It is used to access the attribute data with the values in the request scope. request.getAttribute();
- session scope: It is used to access the attribute data with the values in the session scope. session.getAttribute();
- application scope: It is used to access the attribute data with the values in the application scope. application.getAttribute();
- param: It is used to access a particular request parameter. request.getParameter();
- paramValues: It is used to access more than one parameter value associated with a particular request parameter. request.getParameterValues();
- initParam: It is used to access context parameters from the ServletContext object. application.getInitParameter();
- cookie: It is used to get session id cookie name and session id cookie value. request.getCookies();
- header: It is used to access a particular request header value. request.getHeader();
- headerValues: It is used to access more than one value associated with a single request header. request.getHeaders();
- pageContext: It is used to get all the implicit objects and to get the values from either of the scopes like pageScope, requestScope, applicationScope, and sessonScope.
Example of param and paramValues:
In this example, we have two files form.html and first.jsp. The form.html file gets input from the user and sends the request to the first.jsp which in turn prints the value using EL.
form.html
<!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>Insert title here</title> </head> <body> <b><font size="6"> <form method="get" action="first.jsp"> <br> <br> Name <input type="text" name="uname" /><br> <br> Food Items <select size="3" multiple="true" name="food"> <option value="Orange">Orange</option> <option value="Apple">Apple</option> <option value="Grapes">Grapes</option> </select> <input type="submit" value="Display" /> </form> </font></b> </body> </html>
first.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>Insert title here</title> </head> <body> <b><font size="7"><br> <br> User Name.....${param.uname} <br> <br> Foot Items...<br> ${paramValues.food[0]}<br> ${paramValues.food[1]}<br> ${paramValues.food[2]}<br> </font></b> </body> </html>
Output:
Once you click on the Display button, you will get the below page.
JSP Expression Language SessionScope Example
In this example, we will print the data stored in session scope by using Expression Language in JSP. We are using SessionScope object to print the data.
index.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ page import="java.io.*,java.util.*"%> <!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>Insert title here</title> </head> <body> <h1>WELCOME</h1> <% session.setAttribute("user", "Manisha"); %> <a href="first.jsp">Click Here</a> </body> </html>
first.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>Insert title here</title> </head> <body><h1>Username is ${ sessionScope.user }</h1> </body> </html>
Output
Once you click on the Click Here link, you will get the below page.
JSP Expression Language Cookie Example
In this example, we are printing the data stored in cookies by using cookie object.
index.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ page import="java.io.*,java.util.*"%> <!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>Insert title here</title> </head> <body> <h1>WELCOME</h1> <% Cookie ck=new Cookie("name","Manisha"); response.addCookie(ck); %> <a href="first.jsp">Click Here</a> </body> </html>
first.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>Insert title here</title> </head> <body><h1>Welcome, ${cookie.name.value} </h1> </body> </html>
Output
Once you click on the Click Here link, you will get the below page.
JSP Expression Language ApplicationScope Example
In this example, we are setting the attributes using application object and displaying those attributes using application scope.
index.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ page import="java.io.*,java.util.*"%> <!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>Insert title here</title> </head> <body> <h3>WELCOME</h3> <% application.setAttribute("author", "Manisha"); application.setAttribute("Site", "https://dotnettutorials.net"); %> <a href="first.jsp">Click Here</a> </body> </html>
first.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>Insert title here</title> </head> <body> <h1> ${applicationScope.author}<br> ${applicationScope.Site} </h1> </body> </html>
Output
Once you click on the Click Here link, you will get the below page.
Flow Control Statements in JSP Expression Language
In JSP applications we can easily embed Java where we can use all the APIs of Java and control flow statements of java including decision-making statements as well as looping statements.
Decision Making Statements
In decision-making statements we have to set the conditions either to true or false and the statements behave accordingly.
If-else
In the if-else statement, we are setting some conditions to execute a certain block of code. If the condition is true the “if” block will execute otherwise “else” block will execute.
Example:
In this example, we are testing “if-else” condition by taking variables and checking whether the variables matched with the initialized values or not.
ifelse.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Welcome</title> </head> <body> <%!int month = 10;%> <% if (month == 4) { %> <a>It's April</a> <% } else { %> <a>Any month other than April</a> <% } %> </body> </html>
Output
Switch Case
It is used to check a number of executions where we can give a number of cases to be checked and one default case. It begins with a parameter and executes a certain block of statements whichever is true.
Example:
In this example, we are defining a variable called week which is matched with the true case. In this case, week is 5 hence 5th case is matched and the output is Friday.
switch.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Welcome</title> </head> <body> <%!int week = 5;%> <% switch (week) { case 0: out.println("Sunday"); break; case 1: out.println("Monday"); break; case 2: out.println("Tuesday"); break; case 3: out.println("wednesday"); break; case 4: out.println("Thursday"); break; case 5: out.println("Friday"); break; default: out.println("Saturday"); } %> </body> </html>
Output:
JSP Expression Language Looping Statements
It is the statement that executes more than one statement repeatedly several times.
For Loop
For loop is used to iterate the elements based on certain conditions.
Example:
forloop.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Welcome</title> </head> <body> <%!int num = 10;%> <% out.println("Numbers are:"); for (int i = 0; i < num; i++) { out.println(i); } %> </body> </html>
Output
While Loop
While Loop iterates the elements wherein it has one parameter of the condition.
Example:
In this example, we are using while loop which will iterate till the day us greater than or equal to the counter.
whileloop.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Welcome</title> </head> <body> <%!int day = 7; int i = 1;%> <% while (day >= i) { if (day == i) { out.println("It's Saturday"); break; } i++; } %> </body> </html>
Output
In the next article, I am going to discuss JUnit in JSP Application. Here, in this article, I try to explain Expression Language in JSP with Examples and I hope you enjoy this Expression Language in JSP with Examples article.