javascriptjsprequirejsrequirejs-define

Can I put jsp specific code in an external script file


I would like to get values sent by the Servlet using the HttpSession in an external js file using requirejs' define function:

define(function(){
    return {
        /*Get values from the java session*/
        gisuniqkey:<%=session.getAttribute('gisuniqkey')%>,
        scenario:<%=session.getAttribute('scenario')%>,
        operation:<%=session.getAttribute('operation')%>,
        objkey:<%=session.getAttribute('objkey')%>
    }
});

Is it possible to do this? Any dependencies that I should include when doing this? Eclipse tells me that there is an error when doing this.

The error message simply calls it a syntax error:

 Uncaught SyntaxError: Unexpected token < java_to_script.js:3
 Uncaught TypeError: Cannot read property 'gisuniqkey' of undefined     
 gmaps_createScenario.js:15

All I care is that I do not use a global variable inside my jsp...and that it should work well with require.js,it would be splendid if it could be made a reusable module.


Solution

  • You can't use JSP in a static .js file.

    You can use JSP in a .jsp file that outputs a JavaScript file.

    Output an application/javascript content type, and then write your JS as normal in the .jsp file using JSP directives are you wish.

    Note that, since the JavaScript file will be requested separately to the HTML file you won't be able to read things like the query string used to request the HTML file from the JSP directives in the JavaScript file (although you could pass them via a session, or add them to the src of the <script> element).


    As a rule of thumb, however, it is often better to stick to static JS files and include dynamically generated JS as inline <script> within the HTML document (although keeping such JS to a minimum - just enough to store the data you need). That makes sorting caching rules simpler.