how to access a EL variable and pass it as an argument to a function in EL?

倖福魔咒の 提交于 2019-12-06 14:15:41

Where exactly do you want to do that and for what? Just to get a value for display? At least, in standard EL prior to Java EE 6 you cannot pass method arguments like that. In JBoss-EL or in Java EE 6 EL you can do that. The syntax would then just have been:

${teacherBean.certificationFor(particularField)}

Note that you cannot nest EL expressions, an EL expression is already a whole expression at its own.

In standard EL implementations you can however access Map values by keys using the brace notation. Thus, if you for example have a Map<String, String> certifications where the keys corresponds the particularField and the values the associated value:

private Map<String, String> certifications = new HashMap<String, String>();

public Map<String, String> getCertificationFor() {
    return this.certifications;
}

then you can use the following notation:

${teacherBean.certificationFor[particularField]}

this resolves behind the scenes to

teacherBean.getCertificationFor().get(particularField)

I think in the standard EL you don't have any options other than defining your functions wrapped in a EL function;

Read: http://java.sun.com/j2ee/1.4/docs/tutorial/doc/JSPIntro7.html near the bottom of the document;

but as BalusC mentioned already if you could use another EL implmentation if you have the ability to add that kind of dependency to your app

What about:

${teacherBean.certificationFor(particularField)}

If you are accessing a general functionality that is better expressed as a separate function, then you can write it as follows:

${certificationFor[teacherBean][particularField]}

where certificationFor maps to the CertificationFor class which extends ELMethod.java class. You implement the functionality in the result(Object[] args) method. The args to this method are the args that you passed to the ${certificationFor} object in EL.

public class CertificationFor extends ELMethod {
  public Object result(Object[] args) {  
    TeacherBean teacherBean = (TeacherBean) args[0];  
    String property = (String) args[1];

    // your implementation goes here
    return ....;
  }
}  

The trick is to use your object as a chained map of maps, that is one way to pass multiple args to EL function.

If you are interested, you can see full code and code snippets here: http://www.vineetmanohar.com/2010/07/how-to-pass-parameters-in-el-methods/

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!