JSP Expression Language – JSP EL Example Tutorial

Filed Under: Java EE

Today we will look into JSP Expression Language or JSP EL Example tutorial.

JSP Expression Language – JSP EL

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.

  1. 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.

  2. 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.

  3. JSP EL Arithmetic Operators

    Arithmetic operators are provided for simple calculations in EL expressions. They are +, -, *, / or div, % or mod.

  4. JSP EL Logical Operators

    They are && (and), || (or) and ! (not).

  5. 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

  1. EL expressions are always within curly braces prefixed with $ sign, for example ${expr}
  2. We can disable EL expression in JSP by setting JSP page directive isELIgnored attribute value to TRUE.
  3. JSP EL can be used to get attributes, header, cookies, init params etc, but we can’t set the values.
  4. JSP EL implicit objects are different from JSP implicit objects except pageContext, don’t get confused.
  5. JSP EL pageContext implicit object is provided to get additional properties from request, response etc, for example getting HTTP request method.
  6. JSP EL is NULL friendly, 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.
  7. 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.
  8. If you are using Tomcat, the EL expressions are evaluated using org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate() method.
  9. 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.

JSP EL Example, JSP Expression Language

I have defined some model classes that we will use – Person interface, Employee implementing Person and Address used in Employee.


package com.journaldev.model;

public interface Person {
	
	public String getName();
	public void setName(String nm);
}

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

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.


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.


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://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


<%@ 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" "http://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.

JSP EL, JSP Expression Language, JSP EL Example Tutorial

Comments

  1. Gabriel Czernikier says:

    Here I’ve gotten usefull tips that can’t easily be found in the official docs.

  2. Udayakiran says:

    The cookie value of homeServlet says
    An invalid character [32] was present in the Cookie value

    Doesn’t the cookie accept .dot and spaces ?

  3. SAtish says:

    ${sessionScope.employee.address.address} Why we have two “address” here? Really one of the best articles I have ever consumed on EL. #Gratitude

    1. Abhilash says:

      First “address” is of type “Address” while the second one is a String

  4. saqib says:

    best tutorial on expression language, nobody can beat you in this

  5. big thx says:

    AWESOME TUTORIAL. big THX. Call the HomeServlet so you get redirected to home.jsp.

  6. PowerPlay says:

    Hello Pankaj,
    I read this tutorial, but I have a problem… Let focus on the first jsp’s row. Despite of I set the attribute “person”, when I call it in the jsp throu ${requestScope.person} I get nothing: space on the left of “Simple . EL Example:” stays empty. But I can’t understand why.
    May you help me?
    Thanx!

    1. PowerPlay says:

      Solved!

  7. sunil says:

    How retrieves the value of attribute by name ‘attribute’ in EL expression?

  8. Siddu says:

    Nice Explanation.. I have one doubt in JSP EL, When to use dot operator & [] operator.

    1. Pankaj says:

      As explained, [] operator is more powerful and we can use it for List and Arrays too, another place where [] is more powerful when the attribute name contains dot as given in the example above.

      [] can be nested too, so use dot operator when it satisfies your needs and use [] operator when you need to get data from List, Array or evaluate the expression etc.

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages