Search code examples
javascriptjspjavabeans

put bean values in external JS files


Is there a simply way to read bean values in a .js file?

I have an external JS file, arrays.js, which contains some arrays, used to populate a series of within a JSP page.

Now I need to fill the content of those arrays reading values.

I have to use the external js file, because it also contains lots of other methods to make the application work.

Thank you in advance


Solution

  • Simplest way is to let JSP print it as a global JS variable so that it's visible to the scripts which execute after DOM ready. E.g.

    <script>var bean = ${beanAsJson};</script>
    

    where ${beanAsJson} prints the bean in JSON format. You could use among others Gson for this.

    Another way is to let the JS code send an ajax request to a servlet which writes exactly that bean in JSON format to the response. E.g. with little help of jQuery:

    $.getJSON('jsonServlet', function(bean) {
        // ...
    });
    

    See also: