I have my web application deployed to tomcat with an applicatio context. For example my URL looks something like this.
http://localhost:8080/myapp
myapp - is the application context here.
Now in an Angular service if i want to call a webservice say getusers
. My URL should be this /myapp/getusers
. But I want to avoid hardcoding the application context as it might change from one deployment to other.
I have managed to figureout the contextpath from $window.location.pathname
but it looks very stupid. Is there a betterway?
FYI I am using Spring MVC for restful services.
The typical way of getting the context path is through the HttpServletRequest class. Simply you can add a HttpServletRequest parameter to your controller method and then get the context path using getContextPath() method. Now that you get the context path, you can pass it to the services that need it.
The context path is the prefix of a URL path that is used to select the context(s) to which an incoming request is passed. Context path is also known as sub-path or sub-directory. Many apps are hosted at something other than the root (/) of their domain.
The context path of a web application defines the URL that end users will access the application from. A simple context path like myapp means the web app can be accessed from a URL like http://localhost:8080/myapp.
The $location in AngularJS basically uses a window. location service. The $location is used to read or change the URL in the browser and it is used to reflect that URL on our page. Any change made in the URL is stored in the $location service in AngularJS.
I'm also using tomcat and Spring MVC. Using relative url in JavaScript will do the trick.
For doing this you just need to remove the /
at the begining of REST url. so that your url starts from the current url in your browser.
replace $resource('/getusers')
with $resource('getusers')
For AngularJS $http service you are good to go with url : 'getusers'
, as follows:
$scope.postCall = function(obj) {
$http({
method : 'POST',
url : 'getusers',
dataType : 'json',
headers : {
'Content-Type' : 'application/json'
},
data : obj,
});
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With