EL Features

Back

Loading concept...

Expression Language (EL) Features in Jakarta EE

Your Magical Toolbox for Web Pages đź§°


The Story Begins…

Imagine you have a magic notebook. Whatever you write in special brackets ${ } comes alive! You can add numbers, check conditions, and even transform lists of things—all without writing complicated code.

This magic notebook is called Expression Language (EL) in Jakarta EE. It’s like having a super-smart assistant that lives inside your web pages.


đź”§ EL Operators

The Building Blocks of Magic

Think of operators like the buttons on a calculator. Each button does something special!

Arithmetic Operators (Math Buttons)

Operator What It Does Example Result
+ Adds numbers ${5 + 3} 8
- Subtracts ${10 - 4} 6
* Multiplies ${3 * 4} 12
/ or div Divides ${20 / 5} 4
% or mod Remainder ${7 % 3} 1

Simple Example:

${price * quantity}

If price = 10 and quantity = 3, you get 30!


Comparison Operators (Who’s Bigger?)

Like asking “Is this taller than that?”

Operator Meaning Example
== or eq Equal? ${age == 18}
!= or ne Not equal? ${name != 'Guest'}
< or lt Less than? ${score < 50}
> or gt Greater than? ${score > 90}
<= or le Less or equal? ${age <= 12}
>= or ge Greater or equal? ${age >= 18}

Real Life Example:

${user.age >= 18 ? 'Adult' : 'Child'}

This checks if someone is grown up!


Logical Operators (Decision Makers)

These help you combine questions.

Operator Meaning Example
&& or and Both true? ${logged && admin}
` oror`
! or not Opposite ${!empty name}

Example:

${loggedIn and hasPermission}

Only true if BOTH are true!


The Empty Operator 📦

Checks if something is… well, empty!

${empty cart}

Returns true if:

  • The cart is null
  • The cart has zero items
  • The string is blank

🎯 EL Functions

Pre-Made Magic Spells

Functions are like ready-made recipes. Someone already figured out how to do something—you just use it!

How Functions Work

graph TD A["You Call Function"] --> B["fn:functionName"] B --> C["Pass Your Data"] C --> D["Get Result Back!"]

Common Built-in Functions

String Functions (from JSTL):

Function What It Does Example
fn:length() Count characters ${fn:length('Hello')} → 5
fn:toUpperCase() MAKE IT LOUD ${fn:toUpperCase('hi')} → HI
fn:toLowerCase() make it quiet ${fn:toLowerCase('HI')} → hi
fn:contains() Find inside ${fn:contains('cat','a')} → true
fn:substring() Cut a piece ${fn:substring('Hello',0,2)} → He

Example in Action:

Welcome, ${fn:toUpperCase(user.name)}!

If name is “sam”, shows: Welcome, SAM!


Creating Your Own Functions

You can create custom spells too!

Step 1: Write a Java method (must be static)

public class MyHelper {
    public static String reverse(String s) {
        return new StringBuilder(s)
            .reverse().toString();
    }
}

Step 2: Register it in a TLD file

Step 3: Use it!

${my:reverse('Hello')}

Result: olleH


🎪 Lambda Expressions in EL

Tiny Functions You Write on the Spot

Imagine you could create a mini-recipe RIGHT where you need it. That’s a lambda!

The Arrow -> is Your Friend

(x) -> x * 2

This says: “Take x, give back x times 2”

Breaking It Down

graph LR A["&#35;40;x&#35;41;"] --> B["-&gt;"] B --> C["x * 2"] A -.-> D["Input"] C -.-> E["Output"]

Real Examples

Double a number:

${(x -> x * 2)(5)}

Result: 10

Check if positive:

${(n -> n > 0)(7)}

Result: true

Add two numbers:

${((a, b) -> a + b)(3, 4)}

Result: 7

Why Use Lambdas?

They’re perfect for quick, one-time calculations right where you need them. No need to create a whole function elsewhere!


📚 Collection Operations in EL

Working with Groups of Things

A collection is like a box of toys. You might have a list of users, products, or scores. EL helps you work with them easily!

Accessing Items

By Position (Index):

${fruits[0]}

Gets the first fruit (counting starts at 0!)

By Key (Maps):

${user['name']}

or

${user.name}

Gets the name from user

The Size Trick

${products.size()}

Tells you how many products you have!

Checking Empty Collections

${empty orders}

True if no orders exist

Example: Showing Items

Items in cart: ${cart.size()}
First item: ${cart[0].name}

🌊 Stream API in EL

The Assembly Line for Data

Imagine a factory assembly line. Items go in, get processed step by step, and finished products come out. That’s the Stream API!

graph TD A["📦 Collection"] --> B[".stream"] B --> C["Filter"] C --> D["Transform"] D --> E["Collect"] E --> F["✨ Result"]

Starting a Stream

${items.stream()}

This turns your collection into a flowing river of data!


Filter: Keep Only What You Want

Like a fishing net that catches only certain fish.

${numbers.stream()
    .filter(n -> n > 10)
    .toList()}

Keeps only numbers greater than 10!

Real Example:

${users.stream()
    .filter(u -> u.active)
    .toList()}

Gets only active users!


Map: Transform Each Item

Like a magic wand that changes everything it touches.

${names.stream()
    .map(n -> n.toUpperCase())
    .toList()}

Makes all names UPPERCASE!

Real Example:

${products.stream()
    .map(p -> p.price)
    .toList()}

Gets just the prices from products!


Sorted: Put in Order

Like lining up kids by height.

${scores.stream()
    .sorted()
    .toList()}

Smallest to biggest!

Reverse order:

${scores.stream()
    .sorted((a,b) -> b - a)
    .toList()}

Biggest to smallest!


Reduce: Combine Everything

Like squishing all items into one result.

${numbers.stream()
    .reduce(0, (a,b) -> a + b)}

Adds all numbers together!

Example: Find Total

${prices.stream()
    .reduce(0, (sum, p) -> sum + p)}

Gets the total of all prices!


Count & Average

How many?

${items.stream().count()}

What’s the average?

${scores.stream().average().get()}

Chaining Operations

The real magic happens when you chain operations!

${products.stream()
    .filter(p -> p.price > 50)
    .map(p -> p.name)
    .sorted()
    .toList()}

This:

  1. Filters products over $50
  2. Gets just the names
  3. Sorts them alphabetically
  4. Returns as a list

🎯 Putting It All Together

Here’s a complete example using everything:

<!-- Operators -->
Total: ${price * quantity}

<!-- Functions -->
Hello, ${fn:toUpperCase(user.name)}!

<!-- Lambda -->
Double: ${(x -> x * 2)(price)}

<!-- Collection -->
Items: ${cart.size()}

<!-- Stream -->
Expensive items:
${cart.stream()
    .filter(i -> i.price > 100)
    .map(i -> i.name)
    .toList()}

🌟 Remember This!

Feature Think Of It As… Example
Operators Calculator buttons ${5 + 3}
Functions Ready-made recipes ${fn:length(name)}
Lambdas Instant mini-recipes ${(x -> x*2)(5)}
Collections Box of items ${list[0]}
Streams Assembly line .filter().map()

You Did It! 🎉

You now understand the five superpowers of EL:

  1. Operators - Do math and make decisions
  2. Functions - Use pre-made helpers
  3. Lambdas - Create quick calculations
  4. Collections - Access groups of data
  5. Streams - Process data like a factory

Go build something amazing! Your web pages are now smarter than ever. ✨

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.