JSP Scopes and Expression Language (EL)

1. JSP Scopes

JSP scopes define the visibility and lifetime of variables in JSP pages. There are four major scopes in JSP:

2. JSP Expression Language (EL)

JSP Expression Language (EL) provides a simplified syntax for accessing data in JSP pages. It allows you to express dynamic content in a more readable and concise way.

EL expressions are written between ${} and can be used to access values from various scopes (e.g., page, request, session, application), as well as objects in JavaBeans, collections, or other objects stored in the request.

EL Syntax:


  ${expression}

The ${} syntax is used to evaluate an expression and display its result.

3. EL Expressions Examples:

Here are some examples of EL expressions:

Example: Accessing Variables with EL:


<%-- JSP Page -->
<%
  request.setAttribute("username", "John Doe");
  session.setAttribute("user", "Jane Doe");
  pageContext.setAttribute("title", "Welcome Page");
  application.setAttribute("appName", "CIQ demo app");
%>

<h1>Welcome, ${requestScope.username}</h1>
<p>Your session user is: ${sessionScope.user}</p>
<p>Page Title: ${pageScope.title}</p>
<p>App name: ${application.appName}</p>

3. Implicit Objects in EL

JSP provides several implicit objects that can be accessed in EL expressions. These are pre-defined objects that can be used directly within JSP pages.

Implicit Object Description Example in EL
pageContext Represents the page context, giving access to page-level attributes. ${pageContext.request}
request Represents the HTTP request that the client sent to the server. ${request.parameter["username"]}
session Represents the HTTP session for the current user. ${session.getAttribute("user")}
application Represents the application context, allowing access to application-level attributes. ${application.getAttribute("appName")}
out Represents the output stream used to send data to the client. ${out.println("Hello, World!")}
config Represents the servlet configuration for the current servlet. ${config.getInitParameter("configParam")}
exception Represents an exception thrown during the request processing. ${exception.message}
requestScope Represents the attributes of the current request. ${requestScope.username}
sessionScope Represents the attributes of the current session. ${sessionScope.user}
applicationScope Represents the attributes of the application. ${applicationScope.appName}

Summary of JSP Scopes and EL Expressions

Scope Description EL Example
pageScope Available only within the current page. ${pageScope.title}
requestScope Available within the current request. ${requestScope.username}
sessionScope Available within the current session. ${sessionScope.user}
applicationScope Available throughout the entire application. ${applicationScope.appName}