JSP Expression Language (EL) is a powerful feature in JavaServer Pages (JSP) that allows you to access and manipulate data in a more concise and readable way. EL allows you to access JavaBeans properties, request parameters, session attributes, and other objects, all without needing to write Java code in the JSP page.
Basic Syntax of Expression Language
- Expressions: EL expressions are enclosed in
${}. These expressions are evaluated and replaced with the corresponding values when the page is rendered.
Examples of JSP Expression Language (EL)
1. Displaying a Simple String
You can directly display a string by using EL.
This will output:
2. Accessing Request Parameters
You can access request parameters (such as data from a form submission) in EL.
If the user submits the form with the value "John", the output will be:
3. Accessing Session Attributes
You can access session attributes using EL. For example, assume you have an attribute in the session:
This will display:
4. Accessing Application (Context) Attributes
Similar to session attributes, you can access application attributes using the applicationScope keyword.
This will display:
5. Accessing JavaBeans Properties
You can access properties of JavaBeans using EL. Let's assume you have a User bean with a name property.
In your JSP, you can access the name property of the User bean as follows:
This will display:
6. Accessing Request Attributes
Request attributes (often set by a servlet) can be accessed using requestScope.
This will display:
7. Mathematical Operations
You can perform basic mathematical operations in EL.
This will output:
8. Logical Operations
EL supports logical operators like ==, !=, >, <, &&, ||, etc.
9. Using empty to Check for Empty Values
You can use empty to check if a value is empty, null, or an empty collection.
If user.name is null or empty, it will output:
10. Calling Functions in EL
You can also use built-in functions in EL (such as fn:length, fn:toUpperCase, etc.) if the JSTL functions library is available.
If user.name is "Alice", the output will be:
Conclusion
JSP Expression Language provides a simple, powerful way to interact with JavaBeans, request, session, and application attributes, perform mathematical and logical operations, and format data without the need to write Java code directly in JSP pages. It helps to make JSP pages cleaner, more readable, and maintainable.
Comments
Post a Comment