JSP Expression Language Tutorial (original) (raw)

EL means the Expression Language, which is used for accessing the data and makes it possible to easily access the application data stored in the JavaBean’s components and other objects like request, session, and application etc. The JSP expression language allows a page author to access a bean using a simple syntax such as $(expr).

1. Introduction

The Expression language (EL) has been introduced in JSP 2.0. The main purpose of this EL is to simplify the process of accessing the data from the bean properties and from the implicit objects. By using JSP Expression Language developers can get the data from JavaBeans, Maps, Arrays, and Lists that have been stored as attributes of a web application. Before JSP 2.0, developers could use only Scriptlets, Expressions, or the custom tag to include the server-state in the JSP page output.

1.1 Syntax of Expression Language (EL)

In a JSP, by default, the scripting elements are enabled and EL statement/expressions are disabled. To enable the EL expression in a JSP, developers need to use following page directive.

<%@ page isELIgnored="false"%>

EL Syntax

$(expression)

To get a better idea, on how expression works in a JSP, we will see the below example where EL is used as an operator to add two numbers and get the output.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>

JSP EL Example
Expression is: ${1+2};

At code line no. 10, Expression Language (EL) is set where we are adding the two numbers i.e. 1+2, hence the code will give output as: 3.

When developers will execute the above code, they will have the following output.

Fig. 1: EL Syntax

Fig. 1: EL Syntax Output

1.2 Implicit Objects in Expression Language (EL)

JSP Expression Language (EL) provides many implicit objects that developers can use to get the attributes from different scopes and parameter values.
Note: Do note, these Implicit Objects are different from JSP Implicit Objects and can be used only with JSP EL.
The list is given below.

Implicit Objects Type Description
pageScope Map It maps the given attribute name with the value set in the page scope.
requestScope Map It maps the given attribute name with the value set in the request scope.
sessionScope Map It maps the given attribute name with the value set in the session scope.
applicationScope Map It maps the given attribute name with the value set in the application scope.
param Map It maps the request parameter to the single value.
paramValues Map It maps the request parameter to an array of values.
header Map It maps the request header name to the single value.
headerValues Map It maps the request header name to an array of values.
cookie Map It maps the given cookie name to the cookie value.
initParam Map It maps the initialization parameters.
pageContext pageContext It provides access to many objects i.e. request, session etc.

1.3 Reserve Words in Expression Language (EL)

There are many reserved words in the Expression Language (EL) and the list is given below.

lt le gt ge
eq ne true false
and or not instanceof
div mod empty null

2.1 Tools Used

We are using Eclipse Kepler SR2, JDK 8 and Maven. Having said that, we have tested the code against JDK 1.7 and it works well.

2.2 Project Structure

Firstly, let’s review the final project structure, in case you are confused about where you should create the corresponding files or folder later!

Fig. 2: Expression Language Project Structure

Fig. 2: Expression Language Project Structure

2.3 Project Creation

This section will demonstrate on how to create a Java-based Maven project with Eclipse. In Eclipse IDE, go to File -> New -> Maven Project.

Fig. 3: Create Maven Project

Fig. 3: Create Maven Project

In the New Maven Project window, it will ask you to select project location. By default, ‘Use default workspace location’ will be selected. Just click on next button to proceed.

Fig. 4: Project Details

Fig. 4: Project Details

Select the Maven Web App Archetype from the list of options and click next.

Fig. 5: Archetype Selection

Fig. 5: Archetype Selection

It will ask you to ‘Enter the group and the artifact id for the project’. We will input the details as shown in the below image. The version number will be by default: 0.0.1-SNAPSHOT.

Fig. 6: Archetype Parameters

Fig. 6: Archetype Parameters

Click on Finish and the creation of a maven project is completed. If you observe, it has downloaded the maven dependencies and a pom.xml file will be created. It will have the following code:

pom.xml

4.0.0 JSPELExample JSPELExample 0.0.1-SNAPSHOT war

We can start adding the dependencies that developers want like Junit, Servlet, and JSP API etc. Let’s start building the application!

3. Application Building

Below are the steps involved in developing this application.

3.1 Maven Dependencies

Here, we specify the dependencies for the Servlet and the JSP API. The updated file will have the following code:

pom.xml

4.0.0 JSPELExample JSPELExample war 0.0.1-SNAPSHOT JSPELExample Maven Webapp http://maven.apache.org javax.servlet javax.servlet-api 3.0.1 javax.servlet.jsp jsp-api 2.1 ${project.artifactId}

3.2 Java Class Creation

Let’s create the required Java files. Right-click on src/main/java folder, New -> Package.

Fig. 7: Java Package Creation

Fig. 7: Java Package Creation

A new pop window will open where we will enter the package name as: com.jcg.jsp.el.

Fig. 8: Java Package Name (com.jcg.jsp.el)

Fig. 8: Java Package Name (com.jcg.jsp.el)

Once the package is created in the application, we will need to create the servlet controller and model (i.e. POJO) classes. Right-click on the newly created package: New -> Class.

Fig. 9: Java Class Creation

Fig. 9: Java Class Creation

A new pop window will open and enter the file name as: HomeServlet. The Servlet Controller class will be created inside the package: com.jcg.jsp.el.

Fig. 10: Java Class (HomeServlet.java)

Fig. 10: Java Class (HomeServlet.java)

Repeat the step (i.e. Fig. 9) and create the following model classes i.e. Candidate, Address, and Person.

3.2.1 Implementation of Servlet Controller Class

This is simple servlet controller class where we will set some attributes and add the following code to it:

HomeServlet.java

package com.jcg.jsp.el;

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;

@WebServlet("/myHomeServlet") public class HomeServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    // Setting Some Sample Attributes In The Request Scope
    Person personObj = new Candidate();
    personObj.setName("Harry");
    request.setAttribute("personReqObj", personObj);

    // Setting Some Sample Attributes In The Session Scope
    Candidate candidateObj = new Candidate();
    Address addressObj = new Address();
    addressObj.setAddress("Greece");
    candidateObj.setAddress(addressObj);
    candidateObj.setId(101);
    candidateObj.setName("Java Code Geek");

    HttpSession session = request.getSession();
    session.setAttribute("candidateReqObj", candidateObj);

    // Setting Some Sample Attributes In The Cookie
    Cookie ck = new Cookie("Username.Cookie", "Hi! My Name Is Cookie!");		
    response.addCookie(ck);

    // Setting Some Sample Attributes In The Application Scope
    getServletContext().setAttribute("User.Cookie", "Tomcat User");

    RequestDispatcher dispatcherObj = getServletContext().getRequestDispatcher("/home.jsp");
    dispatcherObj.forward(request, response);
}

}

3.3 Web Deployment Descriptor

In a Java web application, a file named web.xml is known as the Deployment Descriptor. It is an XML file and whenever a request comes to the web server, the web server uses this file to map the URL of the request to a specific code that can handle the request. Add the following code to this file for defining the context initialization parameters.

web.xml

<display-name>JSPELExample</display-name>

<context-param>
    <param-name>AppId</param-name>
    <param-value>150</param-value>
</context-param>

3.4 Creating JSP Views

Right-click on JSPELExample/src/main/webapp folder, New -> JSP File.

Fig. 11: JSP Creation

Fig. 11: JSP Creation

Verify the parent folder location as: JSPELExample/src/main/webapp and enter the filename as: home.jsp. Click Finish.

Fig 12: home.jsp

Fig 12: home.jsp

This is a JSP code using Expression Language (EL) to create the views. Add the following code to it:

home.jsp

<%@ page language="java" contentType="text/html; charset=US-ASCII" pageEncoding="US-ASCII" import="java.util.*"%> <%@ page isELIgnored="false"%>

JSP EL Example <% List dummyNames = new ArrayList(); dummyNames.add("Daniel Atlas"); dummyNames.add("Lucifer Morningstar"); pageContext.setAttribute("names", dummyNames); %>
EL Example?= ${requestScope.personReqObj.name}

EL Example (Without Scope)?= ${personReqObj.name}

Application Scope Example?= ${applicationScope["User.Cookie"]}

Multiple EL Example?= sessionScope.candidateReqObj.id<spanid="pipeSeparator">∣</span>{sessionScope.candidateReqObj.id} <span id="pipeSeparator">|</span> sessionScope.candidateReqObj.id<spanid="pipeSeparator"></span>{sessionScope.candidateReqObj.name} | ${sessionScope.candidateReqObj.address.address}

List EL Example?= names[0]<spanid="pipeSeparator">∣</span>{names[0]} <span id="pipeSeparator">|</span> names[0]<spanid="pipeSeparator"></span>{names[1]}

Header Information EL Example?= ${header["Accept-Encoding"]}

'pageContext' EL Example?= Http Method Is?= ${pageContext.request.method}

Context Param EL Example?= ${initParam.AppId}

Arithmetic Operator EL Example?= ${initParam.AppId + 200}

Relational Operator EL Example?= ${initParam.AppId < 200}

4. Run the Application

As we are ready with all the changes, let us compile the project and deploy the application on the Tomcat7 server. To deploy the application on Tomat7, right-click on the project and navigate to Run as -> Run on Server.

Fig. 13: How to Deploy Application on Tomcat

Fig. 13: How to Deploy Application on Tomcat

Tomcat will deploy the application in its web-apps folder and shall start its execution to deploy the project so that we can go ahead and test it on the browser.

5. Project Demo

Open your favorite browser and hit the following URL. The output page will be displayed.

http://localhost:8085/JSPELExample/code>

Server name (localhost) and port (8085) may vary as per your tomcat configuration. Developers can debug the example and see what happens after every step. Enjoy!

Fig. 14: Application Output

Fig. 14: Application Output

That’s all for this post. Happy Learning!!

6. Conclusion

In this section, developers learned how to create and use the JSP Expression Language (EL) through a simple application. For practice, developers can download the sample application as an Eclipse project from the Downloads section.

7. Download the Eclipse Project

This was an example of Expression Language (EL) in JSP.

Download
You can download the full source code of this example here: JSPELExample

Photo of Yatin

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).