java - get reference to project's base url in static resource file in Spring MVC -


i have bunch of static javascript files handle ajax functions query various parts of application, , deploy multiple versions of application, might have along lines of:

https://www.myurl.com/projectname/ - production release https://www.myurl.com/projectname_alpha/ - current alpha release https://www.myurl.com/projectname_beta/ - current beta release https://www.myurl.com/projectname_unstable/ - current development build 

so if have controller "foo" want make ajax call to, can't hard-code /projectname/foo url (as point production release). currently, inject script each of views gets base url of project global variable:

<script type="text/javascript">     // declare global variable hold project's base url     var baseurl = '<spring:url value="/" />'; </script> 

and reference in javascript files:

var url = baseurl + 'foo/'; 

it's functional, ugly solution, , rather not pollute global namespace if can avoid it. have suggestions how implement better workaround?

to clarify: solution should workable type of request, whether ajax-based or not - calling window.open, setting src attribute of <img> tag, , making ajax call controller should work solution. should applicable regardless of base url or how many layers deep goes, eg:

https://www.myurl.com/ https://www.myurl.com/projectname/ https://www.myurl.com/projectname_alpha/1.2.3/ 

should detected properly.

i'm assuming converting js files jsps not you're looking for.

obvious solution use module system (require.js example) , wrap value in module,

something jsp with:

define({     baseurl: '<c:url value="/" />' }); 

which can required other modules.

this might need quite big reorganization of code code.

a simpler option create following jsp, included in every page:

<script type="text/javascript">     $(document).ready(function () {         $(document).ajaxsend(function (ev, jqxhr, ajaxoptions) {             var context = '${pagecontext.request.contextpath}';             ajaxoptions.url = context + '/' +  ajaxoptions.url;         });     }); </script> 

it prepends context path url of each ajax-request made jquery.

this should work long use urls relative context (that is: starting / , without context name already) in ajax requests.


Comments

Popular posts from this blog

html - How to style widget with post count different than without post count -

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

javascript - storing input from prompt in array and displaying the array -