AngularJS Tutorial: Consuming Java EE Web Services

It’s very common to see people asking how to integrate Java EE applications with some of the popular JavaScript frameworks, specially with AngularJS. In most cases developers already have an application (or a great portion of it) written in Java EE containing all the business logic, and since it’s not feasible to rewrite everything in JavaScript, they look for ways to integrate and add new technology to the project without losing any existing code.

That’s when Web Services comes in handy!! They allow your AngularJS application to send and receive data from the Java EE module in a very easy way. Of course there are more sophisticated ways to do this communication, but that is a subject for another post.

The first step is to expose the Web Service in your Java EE project, I’m assuming that you already have this project ready, but if you don’t, just create one by following the instructions in this link.

Now that you already have your web service, make sure it’s working before you continue, to do that, open your browser and call your service by typing it’s URL, it should follow this pattern:

1
2
3
{domain}:{port}/{projectName}/{webServicePath}
 
//example: http://localhost:8080/WebServiceEJB-war/test

If everything is right the browser will display the data returned by your web service, if it doesn’t you’re probably missing something, make sure you followed every instruction in the example I mentioned above.

Now we can start writing some AngularJS code, after setting up the project let’s create the app.js file like this:

1
2
3
4
5
6
7
var app = angular.module('angularWS',[]);
app.controller('myController', function($scope, $http){
	$http.get('http://localhost:8080/WebServiceEJB-war/test')
		.success(function(data){
			$scope.text = data;		
		});	
});

This is the simplest way to consume a web service with angular, the $http.get function will make the request to the Java EE application, all you need to do is to pass the web service URL, when it receives the data, it will execute the callback passed to the success() function, there you can do anything you want with the data, in my case I’m just assigning it to the $scope.text variable. When your Angular application make the request, it’ll probably get an Cross-Origin Request Blocked error, in this case just follow the steps in this link to fix it.

Recommended for you

Leave a Reply

Your email address will not be published. Required fields are marked *

Obs: Use the tag <pre lang="LANGUAGE"> to include code blocks to your comment.
Example: <pre lang="javascript"> console.log('Test'); </pre>