Skip to content

Instantly share code, notes, and snippets.

@alexfdz
Created January 20, 2013 19:42
Show Gist options
  • Save alexfdz/4581179 to your computer and use it in GitHub Desktop.
Save alexfdz/4581179 to your computer and use it in GitHub Desktop.
JSP Expression Language: Variable input arguments and custom methods declaration
package com.example;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* Extend this class to implement a server side method that takes arguments that
* you would like to call via expression language.
*
* EL call example: ${elEntity[arg1][arg2][argN].method}
*/
public abstract class ELEntity extends HashMap<Object, Object> {
private static final Logger log = LoggerFactory.getLogger(ELEntity.class);
protected List<Object> args = new ArrayList<Object>();
/**
* A new argument to add or a method to execute
* @param key
* @return Itself if an argument has been added or the
* result of a method execution
*/
@Override
public Object get(Object key) {
if(key instanceof String){
Method method = getMethod((String)key);
if(method != null){
return this.executeMethod(method);
}
}
this.args.add(key);
return this;
}
public ELEntity reset(){
args = new ArrayList<Object>();
return this;
}
protected Method getMethod(String name){
Method method = null;
if(StringUtils.isNotEmpty(name)){
try {
method = this.getClass().getMethod(name, null);
} catch (NoSuchMethodException e) {
}
}
return method;
}
protected Object executeMethod(Method method){
Object result = null;
try {
result = method.invoke(this, null);
} catch (IllegalAccessException e) {
log.error("Illegal access on method execution, method:" + method.getName(), e);
} catch (InvocationTargetException e) {
log.error("Invocation error on method execution, method:" + method.getName(), e);
}
this.reset();
return result;
}
}
package com.example;
import java.util.ArrayList;
import java.util.List;
public class ELListBuilder extends ELEntity {
public List build() {
return new ArrayList(args);
}
}
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core_rt" %>
...
<jsp:useBean id="listBuilder" class="com.example.ELListBuilder"/>
<ul>
<c:forEach var="item" items="${listBuilder['red']['yellow']['green'].build}">
<li>${item}</li>
</c:forEach>
</ul>
...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment