Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Absolute VS Relative URLs in a JSP/JavaScript web application

How do you handle URLs in Javascript files in your Java web applications, e.g. when doing AJAX requests?

Do you always use the absolute URL for the AJAX call? (including the web application context) - what if the application context changes?

Or do you use relative URLs? This is difficult because a JSP file could be loaded via multiple different URL mappings in the application.

To make it clearer:

Say I got a java application myapp.war that is running under http://www.example.com/myapp/

In a Javascript file I want to make an AJAX call to /getData.json - I could do this via absolute URL:

$.ajax({
  url: "/myapp/getData.json",
  cache: false
}).done(function(data) {
  ... 
});

this works only as long as I do not rename the app

or via a relative URL

$.ajax({
  url: "getData.json",
  cache: false
}).done(function(data) {
  ... 
});

but the relative URL only works if the current page is in the correct path.

like image 619
Thomas Einwaller Avatar asked May 05 '26 12:05

Thomas Einwaller


1 Answers

Absolute is preferred; consider how often you're going to change your application name vs. the times you'll mess with the file structure (hint: almost never vs. not so rarely, accordingly).

Using absolute paths is also advised by negation; if you're going with relative paths, changing file locations is the least of your problems - think about what happens when you start refactoring your code (which is the quite common): methods, possibly containing brittle URL references, get extracted to utility classes all the time, and such classes will probably lay in other files.

The bottom line is that relative paths will effectively render your code rigid while absolute paths will allow for more flexibility.

like image 89
Eliran Malka Avatar answered May 09 '26 04:05

Eliran Malka