2

I have a web-page created with JavaServer Pages (JSP) and with significant JavaScript (JS) that makes calls to other servers. The URL that the page talks to depends on what server (read: environment) I deploy to.

I have two possible strategies (at least) that I can use.

  1. I can define a server name constant in a JS file and use a script tag on that web page.
  2. I can write a JS variable with the JSP page, as some sort of dynamic content.

I'm leaning heavily on strategy 1, but am unsure if either of these is really better. I'd like to know what best practice is, and why.

1 Answers1

1

I have the same problem, to be honest I have no idea what the 'correct' way to do it is either, but I do hate global vars, so I currently do it this way,

In the jsp,

<script src="${pageContext.request.contextPath}/js/script.min.js"></script>
<script type="text/javascript">
     init('${pageContext.request.contextPath}');
</script>

Then the js is,

function init(baseURL, undefined){
  ...
}

No global vars to worry about then.

Andrew
  • 13,757
  • 13
  • 66
  • 84
  • What if the path isn't the contextPath? – John LeBoeuf-Little Sep 09 '11 at 18:28
  • @John That was just an example, it can anything. I just wanted to show how to avoid using a global javascript var, as that is generally a bad idea. – Andrew Sep 09 '11 at 18:40
  • I guess I mean, if I want to make it a variable on the JSP side, I'm left with some sort of .property file to load, which ends up as a file on the server anyway. In any case, I'm upvoting this since it's a workable approach. Not sure if I'll end up using it. – John LeBoeuf-Little Sep 09 '11 at 19:08