How to Pass Parameters in EL Methods
Join the DZone community and get the full member experience.
Join For FreeThis article describes how to pass any number of parameters in EL functions in 3 simple steps.
Step 1: Extend the class ELMethod
Extend the class ELMethod.java, and implement the following method:
public abstract Object result(Object[] args);
For example, say we want to create a formatDate method which takes 2 arguments
- the format String
- the Date to be formatted
All you need to do is extend the ELMethod class and implement the result(Object[] args) method.
Example
import java.text.SimpleDateFormat;
import java.util.Date;
public class FormatDate extends ELMethod {
private static final long serialVersionUID = 1L;
public FormatDate() {
// number of arguments to the result method
super(2);
}
public Object result(Object[] args) {
String pattern = (String) args[0];
Date date = (Date) args[1];
return new SimpleDateFormat(pattern).format(date);
}
}
Step 2: Add an instance of you class as an application scoped bean
There are many ways to do this, depending on this technology you are using. Here are some examples:
Set request scope in JSP
request.setAttribute("formatDate", new FormatDate());
Set session scope in JSP
session.setAttribute("formatDate", new FormatDate());
Set application scope from Servlet
this.getServletContext().setAttribute("formatDate", new FormatDate())
Set application scope from JSP
<jsp:useBean id="formatDate" class="FormatDate" scope="application" />Set application scope in Seam
Add these annotations to your class
@Name("formatDate")
@Scope(ScopeType.APPLICATION)
Step 3: Call the function via map syntax
Simply pass each argument using the map syntax [] as follows
EL code
${formatDate["MMM, dd"][account.creationDate]}
All arguments passed via EL are sent to the result(Object[] args) method of the FormatDate class.
How does it work
Each argument is collected via the get(Object key) method and is added to an array. When all the arguments have been specified the result method is invoked and the resulting value is returned.
Reference
- Source code of ELMethod.java on my Google Code project. This class is thread safe and can be application scoped.
- FormatDate.java example on my Google Code project
- Add.java example, which adds 2 numbers in EL (e.g. ${add[1][2]})
From http://www.vineetmanohar.com/2010/07/how-to-pass-parameters-in-el-methods
Opinions expressed by DZone contributors are their own.
Trending
-
File Upload Security and Malware Protection
-
Top 10 Pillars of Zero Trust Networks
-
Merge GraphQL Schemas Using Apollo Server and Koa
-
Implementing a Serverless DevOps Pipeline With AWS Lambda and CodePipeline
Comments