Accessing Java Objects and Scoped Attributes Using EL
Course: Advanced Java Training
Topic: Accessing Java Objects and Scoped Attributes Using Expression Language (EL)
Course Link: Advanced Java Training Course
Demo Link: Register for a Free Course Demo
Website: JustAcademy
1. Introduction to Expression Language (EL)
Expression Language (EL) is a feature of Java web technologies that allows developers to access Java objects, bean properties, collections, request parameters, and scoped attributes directly from JSP pages. It reduces the need to write Java code inside HTML and makes JSP pages easier to read and maintain.
In a typical Java web application, servlets and service classes process requests and prepare data, while JSP pages display that data to users. EL provides a convenient way to retrieve the prepared information from the appropriate scope or Java object.
For example, the expression ${customer.name} accesses the name property of an object named customer when that object is available to EL resolution.
Why Use EL?
- Access JavaBean properties without Java scriptlets.
- Read attributes stored in page, request, session, and application scopes.
- Access request parameters and HTTP headers.
- Read values from maps, lists, arrays, and other supported data structures.
- Perform simple arithmetic, logical comparisons, and conditional evaluations.
- Separate presentation logic from business logic.
- Improve JSP readability and maintainability.
2. Learning Objectives
After completing this topic, learners should be able to:
- Explain the purpose and syntax of JSP Expression Language.
- Access JavaBean properties using EL expressions.
- Understand page, request, session, and application scopes.
- Use implicit scope maps to retrieve attributes.
- Access nested objects, maps, arrays, and list elements.
- Retrieve form parameters using EL.
- Use EL operators and empty-value checks.
- Identify common EL errors and apply best practices.
3. Basic Syntax of EL
In JSP pages, the most commonly used EL syntax for immediate evaluation is ${expression}. The JSP container evaluates the expression while processing the page and inserts its resulting value into the response.
Syntax
${expression}
${object.property}
${scopeName.attributeName}
${collection[index]}
Examples
${customer.name}
${requestScope.message}
${sessionScope.loggedInUser}
${applicationScope.siteName}
${param.username}
| Expression |
Purpose |
${customer.name} |
Reads the name property from a resolvable customer object. |
${requestScope.message} |
Reads the message attribute specifically from request scope. |
${sessionScope.loggedInUser} |
Reads an attribute stored in the current HTTP session. |
${applicationScope.siteName} |
Reads an application-wide attribute. |
${param.username} |
Reads the single request parameter named username. |
4. Understanding Java Objects in EL
EL can resolve Java objects made available through supported mechanisms, such as JSP attributes, JavaBeans, and framework-managed objects. A common approach is to create a JavaBean, populate its properties in a servlet, and place the object in a scope for a JSP page to display.
4.1 What Is a JavaBean?
A JavaBean is a Java class commonly used to hold application data. A conventional JavaBean has private properties, public getter and setter methods, and a public no-argument constructor when required by the framework or creation mechanism.
Example: Customer.java
package com.example.model;
public class Customer {
private String name;
private String email;
private int age;
public Customer() {
}
public Customer(String name, String email, int age) {
this.name = name;
this.email = email;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
EL uses JavaBean property conventions to resolve expressions. For example, ${customer.name} normally reads the property through the bean's getName() method. The expression uses the property name, not the method name.
4.2 Accessing Bean Properties in JSP
<h2>Customer Details</h2>
<p>Name: ${customer.name}</p>
<p>Email: ${customer.email}</p>
<p>Age: ${customer.age}</p>
These expressions assume that a suitable attribute named customer is available in an EL-resolvable scope. If the attribute is missing, the result may be empty rather than displaying a useful error message.
5. Preparing a Java Object in a Servlet
A servlet can create or retrieve a Java object and store it as an attribute before forwarding the request to a JSP page.
Example: CustomerServlet.java
package com.example.web;
import java.io.IOException;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import com.example.model.Customer;
@WebServlet("/customer")
public class CustomerServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
Customer customer = new Customer(
"Aarav Sharma",
"[email protected]",
25
);
request.setAttribute("customer", customer);
request.getRequestDispatcher("/customer.jsp")
.forward(request, response);
}
}
The servlet creates the customer object, stores it in request scope using setAttribute(), and forwards the request to the JSP. The JSP can then access the object's properties through EL.
Example: customer.jsp
<%@ page contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Customer Details</title>
</head>
<body>
<h1>Customer Information</h1>
<p>Name: ${requestScope.customer.name}</p>
<p>Email: ${requestScope.customer.email}</p>
<p>Age: ${requestScope.customer.age}</p>
</body>
</html>
Important: This example uses the Jakarta Servlet API, which is common in modern Jakarta EE applications. Older applications may use the javax.servlet.* namespace. Use the namespace supported by your server and dependencies.
6. Understanding Attribute Scopes in JSP
Scopes determine how long an attribute remains available and where it can be accessed. Servlets and JSP pages can store objects as attributes in different scopes, and EL provides implicit scope maps for accessing those attributes.
| Scope |
Attribute API |
EL Scope Map |
Typical Lifetime |
| Page |
pageContext.setAttribute() |
pageScope |
During processing of the current JSP page. |
| Request |
request.setAttribute() |
requestScope |
During the current request, including applicable forwards. |
| Session |
session.setAttribute() |
sessionScope |
Across requests associated with the same HTTP session, until removed or the session expires. |
| Application |
getServletContext().setAttribute() |
applicationScope |
Across the web application's active lifetime, until removed or the application stops. |
7. Page Scope
Page scope stores attributes that are available while the current JSP page is being processed. It is appropriate for temporary values used only by that page.
Example
<%
pageContext.setAttribute("pageMessage", "Welcome to the JSP page");
%>
<p>${pageScope.pageMessage}</p>
The expression ${pageScope.pageMessage} explicitly reads the attribute from page scope. In production applications, prefer preparing data in a servlet or controller instead of placing Java scriptlets in JSP pages.
8. Request Scope
Request scope stores data for a single request. It is commonly used when a servlet prepares information and forwards the request to a JSP page. The request attributes are not automatically preserved as request attributes across a separate browser request or redirect.
Servlet Example
request.setAttribute("message", "Customer record loaded");
request.setAttribute("recordCount", 5);
request.getRequestDispatcher("/dashboard.jsp")
.forward(request, response);
JSP Example
<p>${requestScope.message}</p>
<p>Records found: ${requestScope.recordCount}</p>
Request scope is useful for page-specific messages, validation errors, search results, and data needed only during the current request.
9. Session Scope
Session scope stores attributes associated with a user's HTTP session. It is commonly used for information such as a shopping cart, login-related application state, or user preferences. Do not store unnecessary or sensitive information in the session, and do not treat the existence of a session attribute alone as complete authorization.
Servlet Example
request.getSession().setAttribute(
"displayName",
"Aarav"
);
JSP Example
<p>Welcome, ${sessionScope.displayName}</p>
Session attributes may be shared by concurrent requests from the same session. Avoid placing mutable shared objects in the session without considering thread safety and synchronization.
10. Application Scope
Application scope stores attributes in the web application's ServletContext. These attributes may be accessed across requests and sessions within the same web application. Use this scope for application-wide data that is appropriate to share, rather than for individual users' private information.
Servlet Example
getServletContext().setAttribute(
"applicationName",
"Customer Management System"
);
JSP Example
<p>Application: ${applicationScope.applicationName}</p>
Application-scoped attributes may be accessed concurrently by many requests. Mutable shared values require appropriate thread-safety controls.
11. Accessing Attributes Without Explicit Scope
An expression such as ${message} searches for an attribute named message through the standard JSP scope order: page, request, session, and application. It resolves the first matching attribute it finds.
${message}
For clarity and to avoid unexpected results when the same attribute name exists in multiple scopes, use an explicit scope whenever the intended location matters.
${requestScope.message}
${sessionScope.message}
${applicationScope.message}
| Expression |
Meaning |
${message} |
Finds the first matching attribute in the standard scope search order. |
${pageScope.message} |
Reads only from page scope. |
${requestScope.message} |
Reads only from request scope. |
${sessionScope.message} |
Reads only from session scope. |
${applicationScope.message} |
Reads only from application scope. |
12. Accessing Nested Java Objects
EL supports property navigation through nested objects. If a customer has an address property and the address object has a city property, EL can navigate through both objects.
Example Java Classes
public class Address {
private String city;
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
public class Customer {
private String name;
private Address address;
public String getName() {
return name;
}
public Address getAddress() {
return address;
}
public void setName(String name) {
this.name = name;
}
public void setAddress(Address address) {
this.address = address;
}
}
JSP Expression
<p>Customer: ${customer.name}</p>
<p>City: ${customer.address.city}</p>
The nested expression assumes that the customer and address objects are present and that the relevant properties can be resolved. If an intermediate object is null, the expression will not produce the expected city value; validate or prepare the data in the controller before rendering.
13. Accessing Maps, Lists, and Arrays
EL supports bracket notation for accessing elements in collections and maps. This is helpful when the property or key is dynamic or when the key contains characters that are unsuitable for dot notation.
13.1 Accessing a Map
<%
java.util.Map<String, String> details =
new java.util.HashMap<>();
details.put("department", "IT");
details.put("location", "Mumbai");
request.setAttribute("details", details);
%>
<p>Department: ${requestScope.details['department']}</p>
<p>Location: ${requestScope.details['location']}</p>
For cleaner JSP architecture, create and populate the map in the servlet or service layer rather than using scriptlets.
13.2 Accessing a List
<%
java.util.List<String> skills =
java.util.Arrays.asList("Java", "JSP", "JDBC");
request.setAttribute("skills", skills);
%>
<p>First skill: ${requestScope.skills[0]}</p>
<p>Second skill: ${requestScope.skills[1]}</p>
13.3 Accessing an Array
<p>First item: ${requestScope.products[0]}</p>
Indexes are zero-based. For example, index 0 refers to the first item in a list or array.
14. Using EL Implicit Objects
JSP EL provides implicit objects for accessing common request data and scope attributes without manually creating those objects. The most useful implicit objects for this topic are scope maps and request-related maps.
| Implicit Object |
Purpose |
Example |
pageScope |
Accesses page-scoped attributes. |
${pageScope.notice} |
requestScope |
Accesses request-scoped attributes. |
${requestScope.customer} |
sessionScope |
Accesses session-scoped attributes. |
${sessionScope.cart} |
applicationScope |
Accesses application-scoped attributes. |
${applicationScope.siteName} |
param |
Reads one request parameter value. |
${param.username} |
paramValues |
Reads all values for a request parameter. |
${paramValues.category[0]} |
header |
Reads a single HTTP request header. |
${header["User-Agent"]} |
cookie |
Looks up a request cookie by name. |
${cookie.theme.value} |
initParam |
Reads a context initialization parameter. |
${initParam.supportEmail} |
pageContext |
Provides access to the JSP PageContext object. |
${pageContext.request.contextPath} |
Implicit objects are predefined EL names. Avoid using these reserved names as ordinary variable names in your page code.
15. Accessing Request Parameters Using EL
Request parameters commonly come from HTML forms and query strings. EL's param object retrieves a single value for a named parameter.
HTML Form
<form action="welcome.jsp" method="get">
<label for="username">Username:</label>
<input type="text" id="username" name="username">
<button type="submit">Submit</button>
</form>
JSP Page
<p>Submitted username: ${param.username}</p>
For a parameter with multiple values, such as a group of checkboxes sharing the same name, use paramValues. Request parameters are user-controlled input, so validate them on the server and encode any output appropriately.
16. Using EL Operators
EL supports arithmetic, comparison, logical, and empty-value operators. These are useful for simple presentation decisions and displaying calculated values.
| Operator |
Alternative |
Example |
+ |
— |
${5 + 3} |
- |
— |
${10 - 4} |
* |
— |
${4 * 3} |
/ |
div |
${12 div 3} |
% |
mod |
${10 mod 3} |
== |
eq |
${status eq 'ACTIVE'} |
!= |
ne |
${status ne 'DISABLED'} |
> |
gt |
${score gt 50} |
< |
lt |
${age lt 18} |
>= |
ge |
${quantity ge 1} |
<= |
le |
${price le 1000} |
&& |
and |
${active and verified} |
|| |
or |
${admin or manager} |
! |
not |
${not active} |
empty |
— |
${empty requestScope.errors} |
Example: Conditional Display
<p>
${requestScope.score ge 50
? 'Result: Pass'
: 'Result: Fail'}
</p>
The conditional operator is useful for short display expressions. More complex business rules should be evaluated in Java application code before forwarding to the JSP.
17. Checking for Missing or Empty Attributes
The empty operator checks whether a value is null, an empty string, an empty collection, or an empty map, among other supported cases. It is useful when deciding whether to show optional content.
<%-- Display a message if the request attribute is missing or empty --%>
<c:if test="${empty requestScope.message}">
<p>No message is available.</p>
</c:if>
<c:if test="${not empty requestScope.message}">
<p>${requestScope.message}</p>
</c:if>
The example uses JSTL's core tag library. Make sure the appropriate JSTL dependency and taglib declaration are configured for your server and application version.
18. Iterating Through a Collection with JSTL
When a servlet supplies a list of objects, JSTL's c:forEach tag can iterate through it and EL can read each object's properties. This approach is commonly used to display database query results in a table.
Servlet Preparation
request.setAttribute("customers", customerList);
request.getRequestDispatcher("/customers.jsp")
.forward(request, response);
JSP Display
<%@ taglib prefix="c" uri="jakarta.tags.core" %>
<table border="1" cellpadding="8" cellspacing="0">
<tr>
<th>Name</th>
<th>Email</th>
<th>Age</th>
</tr>
<c:forEach var="customer"
items="${requestScope.customers}">
<tr>
<td><c:out value="${customer.name}"/></td>
<td><c:out value="${customer.email}"/></td>
<td><c:out value="${customer.age}"/></td>
</tr>
</c:forEach>
</table>
The tag library URI shown is used by Jakarta Tags in modern Jakarta EE environments. Older JSTL deployments may use a different URI, such as http://java.sun.com/jsp/jstl/core; follow the version installed in your application.
19. Forwarding Versus Redirecting
Understanding the difference between forwarding and redirecting is important when working with request-scoped attributes.
| Feature |
Forward |
Redirect |
| Mechanism |
Server forwards processing to another resource. |
Server sends a redirect response, and the browser makes another request. |
| Request attributes |
Remain available during the forwarded request. |
Are not automatically carried into the new request. |
| Browser URL |
Normally remains the original URL. |
Changes to the redirect target URL. |
| Typical use |
Display results or validation errors. |
Redirect after successful form submission. |
Forward Example
request.setAttribute("message", "Saved successfully");
request.getRequestDispatcher("/result.jsp")
.forward(request, response);
Redirect Example
response.sendRedirect(
request.getContextPath() + "/result"
);
After a redirect, use an appropriate persistence mechanism if data must be available on the next request. The Post/Redirect/Get pattern is often used to avoid accidental duplicate form submissions.
20. Common Errors and Troubleshooting
| Problem |
Possible Cause |
Solution |
| EL expression displays no value. |
Attribute is missing or has a different name. |
Check the attribute name, scope, and servlet execution path. |
| Nested property is unavailable. |
An intermediate object is null or the property cannot be resolved. |
Check object initialization and JavaBean getter methods. |
| Request attribute disappears. |
The application redirects or makes a new request. |
Use a forward when appropriate, or deliberately transfer required data. |
| Wrong value appears. |
The same attribute name exists in multiple scopes. |
Use an explicit scope such as requestScope or sessionScope. |
| JSTL tag is not recognized. |
Missing dependency or incorrect taglib URI. |
Configure the compatible JSTL/Jakarta Tags library and URI. |
| EL is shown as literal text. |
EL evaluation is disabled or the page is configured for compatibility. |
Review JSP configuration and page directives. |
| Unexpected output appears in the page. |
Raw user input is inserted into HTML. |
Use context-appropriate output encoding; consider JSTL c:out for HTML text. |
| Session data appears inconsistent. |
Session expiry, attribute replacement, or concurrent requests. |
Review session lifecycle and mutable shared state. |
21. Security Best Practices
- Validate user input: EL is not a substitute for server-side validation.
- Encode output: Never assume values from request parameters, database fields, or user profiles are safe HTML.
- Use safe output mechanisms: For HTML text, JSTL
c:out can escape XML-sensitive characters by default.
- Avoid exposing sensitive data: Do not display passwords, tokens, internal identifiers, or confidential attributes in JSP pages.
- Keep business logic out of JSP: Perform authorization, validation, and business decisions in server-side application code.
- Limit session contents: Store only the data needed for the session and remove attributes when they are no longer required.
- Use explicit scopes: Make data access clear and prevent accidental resolution of an unintended attribute.
- Protect shared state: Application-scoped and session-scoped mutable objects may be accessed concurrently.
22. Best Practices for Writing Maintainable JSP Pages
- Use servlets or controllers to prepare data and forward it to JSP pages.
- Use JavaBeans or suitable model objects for structured application data.
- Use EL for straightforward property access and simple presentation expressions.
- Prefer explicit scope references when the intended scope is important.
- Use JSTL tags for common conditions and collection iteration.
- Keep JSP pages focused on presentation rather than database access.
- Use descriptive attribute names such as
customerList, validationErrors, and currentUser.
- Test cases where attributes are null, empty, or absent.
23. Practical Exercise: Customer Information Display
Objective: Build a small servlet-and-JSP application that displays customer information using EL and scoped attributes.
Requirements
- Create a JavaBean named
Customer with name, email, and age properties.
- Create a servlet mapped to
/customer.
- Create a customer object in the servlet or retrieve one from a service.
- Store the customer object in request scope with the attribute name
customer.
- Forward the request to
customer.jsp.
- Display the customer's properties using
${requestScope.customer.name}, ${requestScope.customer.email}, and ${requestScope.customer.age}.
- Add a conditional message using JSTL to handle a missing customer.
- Test the application with both valid and missing data.
Expected Output
Customer Information
Name: Aarav Sharma
Email: [email protected]
Age: 25
Extension Tasks
- Add an address object and display its city through nested EL navigation.
- Create a list of customers and render it using
c:forEach.
- Display a request-scoped success message.
- Add a session-scoped display preference.
- Test how a redirect differs from a forward when displaying request attributes.
24. Interview Questions and Answers
Q1. What is Expression Language in JSP?
Answer: Expression Language is a concise syntax used in JSP to access JavaBean properties, scoped attributes, request parameters, collections, and other supported values without embedding Java scriptlets in the page.
Q2. What is the syntax of EL?
Answer: The common immediate-evaluation syntax in JSP is ${expression}. For example, ${customer.name} accesses a bean property.
Q3. What is a scoped attribute?
Answer: A scoped attribute is an object or value stored in a defined scope, such as page, request, session, or application scope.
Q4. What are the four standard JSP attribute scopes?
Answer: Page, request, session, and application.
Q5. What is the difference between ${message} and ${requestScope.message}?
Answer: The unqualified expression searches the standard scopes in order. The explicit expression reads only the request-scoped attribute named message.
Q6. How does EL access a JavaBean property?
Answer: EL uses JavaBean property resolution, typically through a public getter. For example, ${customer.name} resolves the name property through getName().
Q7. What is the difference between request scope and session scope?
Answer: Request scope is associated with the current request, while session scope allows an attribute to persist across multiple requests associated with the same HTTP session.
Q8. When should application scope be used?
Answer: Use application scope for data intentionally shared across requests and users within a web application, such as suitable application-wide configuration or shared reference data.
Q9. How can EL access a map value?
Answer: Use bracket notation, such as ${requestScope.details['department']}.
Q10. What does the EL empty operator do?
Answer: It checks whether a value is null or empty, including supported empty strings, arrays, collections, and maps.
Q11. Can EL replace all Java business logic?
Answer: No. EL is intended for data access and simple presentation expressions. Complex business rules, database operations, validation, and authorization belong in server-side Java components.
Q12. How should user-provided text be displayed safely?
Answer: Validate input on the server and use output encoding appropriate to the destination context. For HTML text, JSTL c:out is a useful option.
25. Quick Revision Checklist
- EL commonly uses the
${...} syntax in JSP pages.
${customer.name} reads a JavaBean property when the object is resolvable.
pageScope, requestScope, sessionScope, and applicationScope expose scoped attributes.
- Unqualified attributes are searched in page, request, session, and application scope order.
param accesses one request parameter; paramValues accesses multiple values.
- Bracket notation supports map keys and indexed collection access.
- A forward retains request attributes for the forwarded request; a redirect starts a new request.
- JSTL supports common conditions and collection iteration.
- Validate user input and encode output to help prevent cross-site scripting.
- Keep complex application logic in servlets, controllers, services, and model classes.
26. Conclusion
Accessing Java objects and scoped attributes using Expression Language is an essential skill for developing maintainable JSP applications. EL connects presentation pages with application data through concise expressions, while the four scopes determine how long attributes remain available and where they can be accessed.
By combining JavaBeans, servlet-managed attributes, EL, and JSTL, developers can create readable dynamic pages without relying on Java scriptlets. Clear scope selection, correct object preparation, and secure output handling help ensure that JSP applications remain reliable and easier to maintain.
Learn More with JustAcademy
Explore the Advanced Java Training Course to learn more about Java web development, Servlets, JSP, JDBC, and enterprise application concepts.
Register for a Course Demo to learn about the training program.
Visit the JustAcademy official website to explore additional courses and learning resources.