Friday, March 21, 2008

how to access constants from JSTL (EL)

During our web development we may come across a situation where we want to use a constant (static final) variable for some reason in our JSP using JSTL's Expression Language (EL). As you know we access properties very easily using JSTL as below.

you might alreay know.. if we want to access a property called studentName and a method is defined as getStudentName() in the target object (lets cal it 'student') the EL would be "${student.studentName}".

But if we want to access a constant defined in the above class as
public static int MAX_RETRY_ATTEMPTS=10;

using the EL "${student.MAX_RETRY_ATTEMPTS}" , will fail
I am sure you will need to use these constants sometimes.

We can use a simple trick to solve this.

we will make use of a Map to store the constants , as below


.....
.....
......
public final static int MAX_ALLOWED_USERS=10;
public final static int MAX_LOGIN_ATTEMPTS=2;
Map constants=new HashMap();

public Map getConstants(){
constants.put("MAX_ALLOWED_USERS", MAX_ALLOWED_USERS);
constants.put("MAX_LOGIN_ATTEMPTS", MAX_LOGIN_ATTEMPTS);
return constants;
}


As you can see we have defined a method getConstants which returns a HashMap with our constants with appropriate keys.

Now how can we use this in our JSP ?


The Maximum number of attempts is : "${MyForm.constants['MAX_LOGIN_ATTEMPTS']}"


clearly, we first get the Map using getConstants() method and then value of the constant using the key 'MAX_LOGIN_ATTEMPTS'.

Easy ?

Please let me know if there is a better way to do this

No comments: