Today we will look into JSP Expression Language or JSP EL Example tutorial.
JSP Expression Language – JSP EL
Most of the times we use JSP for view purposes and all the business logic is present in servlet code or model classes. When we receive client request in a servlet, we process it and then add attributes in request/session/context scope to be retrieved in JSP code. We also use request params, headers, cookies and init params in JSP to create response views.
We saw in earlier posts, how we can use scriptlets and JSP expressions to retrieve attributes and parameters in JSP with java code and use it for view purpose. But for web designers, java code is hard to understand and that’s why JSP Specs 2.0 introduced Expression Language (EL) through which we can get attributes and parameters easily using HTML like tags.
Expression language syntax is ${name}
and we will see how we can use them in JSP code.
Read: JSP Tutorial for Beginners
JSP EL Implicit Objects
JSP Expression Language provides many implicit objects that we can use to get attributes from different scopes and parameter values. The list is given below.
JSP EL Implicit Objects | Type | Description |
---|---|---|
pageScope | Map | A map that contains the attributes set with page scope. |
requestScope | Map | Used to get the attribute value with request scope. |
sessionScope | Map | Used to get the attribute value with session scope. |
applicationScope | Map | Used to get the attributes value from application scope. |
param | Map | Used to get the request parameter value, returns a single value |
paramValues | Map | Used to get the request param values in an array, useful when request parameter contain multiple values. |
header | Map | Used to get request header information. |
headerValues | Map | Used to get header values in an array. |
cookie | Map | Used to get the cookie value in the JSP |
initParam | Map | Used to get the context init params, we can’t use it for servlet init params |
pageContext | pageContext | Same as JSP implicit pageContext object, used to get the request, session references etc. example usage is getting request HTTP Method name. |
Note that these implicit objects are different from JSP implicit objects and can be used only with JSP EL.
JSP Expression Language – JSP EL Operators
Let’s look at EL Operators and understand how they are interpreted and how to use them.
-
EL Property Access Operator or Dot (.) Operator
JSP EL Dot operator is used to get the attribute values.
${firstObj.secondObj}
In the above expression, firstObj can be EL implicit object or an attribute in page, request, session or application scope. For example,
${requestScope.employee.address}
Note that except the last part of the EL, all the objects should be either Map or Java Bean, so in above example, requestScope is a Map and employee should be a Java Bean or Map. If the scope is not provided, the JSP EL looks into page, request, session and application scope to find the named attribute.
-
JSP EL [] Operator or Collection Access Operator
The [] operator is more powerful than the dot operator. We can use it to get data from List and Array too.
Some examples;
${myList[1]} and ${myList[“1”]} are same, we can provide List or Array index as String literal also.
${myMap[expr]} – if the parameter inside [] is not String, it’s evaluated as an EL.
${myMap[myList[1]]} – [] can be nested.
${requestScope[“foo.bar”]} – we can’t use dot operator when attribute names have dots.
-
JSP EL Arithmetic Operators
Arithmetic operators are provided for simple calculations in EL expressions. They are +, -, *, / or div, % or mod.
-
JSP EL Logical Operators
They are && (and), || (or) and ! (not).
-
JSP EL Relational Operators
They are == (eq), != (ne), < (lt), > (gt), <= (le) and >= (ge).
JSP Expression Language – JSP EL Operator Precedence
JSP EL expressions are evaluated from left to right. JSP EL Operator precedence is listed in below table from highest to lowest.
JSP EL Operator Precedence from Highest to Lowest |
---|
[ ] . |
() – Used to change the precedence of operators. |
– (unary) not ! empty |
* / div % mod |
+ – (binary) |
< > <= >= lt gt le ge |
== != eq ne |
&& and |
|| or |
? : |
JSP Expression Language – JSP EL Reserve Words
and | or | not | eq | ne |
---|---|---|---|---|
lt | gt | le | ge | true |
false | null | instanceof | empty | div,mod |
Above are the reserved words, don’t use them as an identifier in JSPs.
JSP Expression Language Important Points
- EL expressions are always within curly braces prefixed with $ sign, for example ${expr}
- We can disable EL expression in JSP by setting JSP page directive isELIgnored attribute value to TRUE.
- JSP EL can be used to get attributes, header, cookies, init params etc, but we can’t set the values.
- JSP EL implicit objects are different from JSP implicit objects except pageContext, don’t get confused.
- JSP EL pageContext implicit object is provided to get additional properties from request, response etc, for example getting HTTP request method.
- JSP EL is NULL frie
ndly, if given attribute is not found or expression returns null, it doesn’t throw any exception. For arithmetic operations, EL treats null as 0 and for logical operations, EL treats null as false. - The [] operator is more powerful than dot operator because we can access list and array data too, it can be nested and argument to [] is evaluated when it’s not string literal.
- If you are using Tomcat, the EL expressions are evaluated using
org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate()
method. - We can use EL functions to call method from a java class, more on this in custom tags post in near future.
JSP EL Example
Let’s see EL usage with a simple application. We will set some attributes in different scopes and use EL to retrieve them and show in JSP page. Our project structure will be like below image.
I have defined some model classes that we will use – Person interface, Employee implementing Person and Address used in Employee.
1 2 3 4 5 6 7 |
package com.journaldev.model; public interface Person { public String getName(); public void setName(String nm); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
package com.journaldev.model; public class Address { private String address; public Address() { } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String toString(){ return "Address="+address; } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
package com.journaldev.model; public class Employee implements Person { private String name; private int id; private Address address; public Employee() { } @Override public String getName() { return this.name; } @Override public void setName(String nm) { this.name = nm; } public int getId() { return id; } public void setId(int id) { this.id = id; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } @Override public String toString(){ return "ID="+id+",Name="+name+",Address="+address; } } |
Notice that Employee and Address are java beans with the no-args constructor and getter-setter methods for properties. I have also provided an implementation of toString() method that we will use in JSP page.
Now let’s see the code of a simple servlet that will set some attributes.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
package com.journaldev.servlet; import java.io.IOException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.journaldev.model.Address; import com.journaldev.model.Employee; import com.journaldev.model.Person; @WebServlet("/HomeServlet") public class HomeServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //Setting some attributes Person person = new Employee(); person.setName("Pankaj"); request.setAttribute("person", person); Employee emp = new Employee(); Address add = new Address(); add.setAddress("India"); emp.setAddress(add); emp.setId(1); emp.setName("Pankaj Kumar"); HttpSession session = request.getSession(); session.setAttribute("employee", emp); response.addCookie(new Cookie("User.Cookie","Tomcat User")); getServletContext().setAttribute("User.Cookie","Tomcat User"); RequestDispatcher rd = getServletContext().getRequestDispatcher("/home.jsp"); rd.forward(request, response); } } |
Let’s define some context init params in the web.xml deployment descriptor.
1 2 3 4 5 6 7 8 9 10 |
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xmlns="https://java.sun.com/xml/ns/javaee" xsi:schemaLocation="https://java.sun.com/xml/ns/javaee https://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"> <display-name>JSPELExample</display-name> <context-param> <param-name>AppID</param-name> <param-value>123</param-value> </context-param> </web-app> |
JSP code using EL to create views:
home.jsp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
<%@ page language="java" contentType="text/html; charset=US-ASCII" pageEncoding="US-ASCII" import="java.util.*"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"> <title>JSP EL Example Home</title> </head> <body> <% List<String> names = new ArrayList<String>(); names.add("Pankaj");names.add("David"); pageContext.setAttribute("names", names); %> <strong>Simple . EL Example:</strong> ${requestScope.person} <br><br> <strong>Simple . EL Example without scope:</strong> ${person} <br><br> <strong>Simple [] Example:</strong> ${applicationScope["User.Cookie"]} <br><br> <strong>Multiples . EL Example:</strong> ${sessionScope.employee.address.address} <br><br> <strong>List EL Example:</strong> ${names[1]} <br><br> <strong>Header information EL Example:</strong> ${header["Accept-Encoding"]} <br><br> <strong>Cookie EL Example:</strong> ${cookie["User.Cookie"].value} <br><br> <strong>pageContext EL Example:</strong> HTTP Method is ${pageContext.request.method} <br><br> <strong>Context param EL Example:</strong> ${initParam.AppID} <br><br> <strong>Arithmetic Operator EL Example:</strong> ${initParam.AppID + 200} <br><br> <strong>Relational Operator EL Example:</strong> ${initParam.AppID < 200} <br><br> <strong>Arithmetic Operator EL Example:</strong> ${initParam.AppID + 200} <br><br> </body> </html> |
When we send a request for the above servlet, we get output like below image.