Codebox Software

Accessing JSP values from JavaScript

Published:

This technique provides a safe and easy way to access data held in JSP variables from JavaScript. The normal method for doing this involves putting some code like this in your JSP file:

var num = <c:out value="${accountNumber}" />;

which would make a line in the resulting HTML file something like this:

var num = 123456;

This does indeed have the desired effect - the value of the JSP variable accountNumber is written to the JavaScript variable num and thereafter can be used from within JavaScript code on the page. However, there is a problem with this approach - namely that if, for some reason, the JSP variable (accountNumber in our example) does not exist, then the resulting code is no longer valid JavaScript and will cause a syntax error:

var num = ; // JSP 'accountNumber' variable did not exist

The jspArgs object declared below can be used as a safe container for JSP variable values, overcoming the problem described:

var jspArgs = (function(){
    var jspArgsValues = {}; // Values stored here, protected by a closure
    var jspArgsObj = {};    // This gets augmented and assigned to jspArgs

    jspArgsObj.set = function(name){
        return function(value){
            name && (jspArgsValues[name] = value);
        };
    };

    jspArgsObj.get = function(name){
        return jspArgsValues[name];
    };

    return jspArgsObj;
})();

The object is used as follows:

jspArgs.set('num')(<c:out value="${accountNumber}" />); // stores the value of 'accountNumber' inside jspArgs

...

var num = jspArgs.get('num'); // retrieves the value 

Pay particular attention to the syntax of the jspArgs.set function call, it is unusual:

jspArgs.set('num')(123456);

The set method accepts the name of the value that you are storing as its argument, and then it returns a function which accepts the value to be stored as its argument. The code above above could be written more verbosely as follows:

var putValueHereFunction = jspArgs.set('num');
putValueHereFunction(123456);

but the shorthand version is much more readable. Splitting the set operation into 2 parts in this way has the advantage that the resulting JavaScript code is still valid if either (or both) arguments are omitted:

jspArgs.set('num')(123456);
jspArgs.set()(123456);
jspArgs.set('num')();
jspArgs.set()();