How to pass parameters in EL methods

This 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

  1. the format String
  2. 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]})

Related posts:

  1. Calling a static method from EL
  2. How to copy bean properties with a single line of code
  3. JAXB code snippets for beginners
  4. 2 ways to convert Java Map to String
  5. Java Barcode API

Leave a Reply

 

 

 

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Get Adobe Flash playerPlugin by wpburn.com wordpress themes