How to call Java RESTful services in secured way from AngularJS

1,667 views
Skip to first unread message

Jayanta Pramanik

unread,
Jul 6, 2014, 1:41:24 AM7/6/14
to ang...@googlegroups.com
Hi,

I am just new in Angular JS. Now involved in creating one secured application that will consume RESTservices (written in Java resteasy) from server application. I'm able to call RESTful service using $http.jsonp but I don't know whether it is how much secured. Therefore I want to use POST method.

I was trying to call using $http.post but it is not known to me how to call service along with passing values to it. 

Here is code snippet for my REST Service as given below -

@Path("/GatewayService")
public class GatewayServiceImpl implements GatewayService {

@PersistenceContext 
private EntityManager entityManager;
@Override
@Path("/fetchDetails/{accountno}")     
@POST
@Consumes("application/json")
@Produces({"application/json"}) 
public WbWebGenericEntity fetchDetails(String accountno) {
WbWebGenericEntity genericEntity = new WbWebGenericEntity();
try {
genericEntity.setAccountnumber("8902688190");        /// some hard coded values are set into the property
genericEntity.setAccountname("JAYANTA PRAMANIK");
catch(Exception e){
e.printStackTrace();
}
/*catch (JAXBException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
return genericEntity;
}


And here is my Angular JS call to this REST service -


/*
 *  ----- Controller.js
 *  ----- Required dependencies are injected into the controller’s signature
 */
function MyAccountController($scope, $http, GenericService){

    $scope.findAccountInfo = function () {
        $scope.removeFetchedData();
        $scope.getAccountInfo();         //// Calling Service from this function
        console.log($scope.fetchedData);
    }

    $scope.getAccountInfo = function () {
        GenericService.getAcctInfo('8902688190').success(function(summaryDetail){
            alert(summaryDetail);
        })
    }

    $scope.removeFetchedData = function () {
        alert('removeFetchedData --------');
        $scope.fetchedData=[];
    }

}

/*
 *  -------- Services.js
 * --------  All required services are written here
 */

//ROUTING WITH IN INDEX PAGE
var myModule = angular.module('myModule', [])
    .config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) {
        $routeProvider.
            when('/videos', {templateUrl: 'myPages/Welcome.html'}).
            when('/videos/logout', {templateUrl: 'login.html'}).
            . . .
            . . . . .

            otherwise({redirectTo: '/videos'});

    }]);


////---- WRITING SERVICE FACTORY TO CONSUME WEB SERVICE ---- ////

myModule.factory('GenericService', ['$http', function($http) {
    var service = {
        getAcctInfo: function (acctno) {
            alert("Here inside factory method");
            console.log("Account No : " + acctno);
            var accountInfo = {};
            accountInfo.accountno=acctno;

            $http({method: 'POST', url: 'http://localhost:8080/demoapp/service/GatewayService/'}).
                success(function(data, status, headers, config) {
                           /// some actions taken
                }).
                error(function(data, status, headers, config) {
                          //// Some messages logged
                });
        }
    };
    return service;
}]);


Please any body help me. I need this REST service (as above) to call from Angular JS using $http.post 
Is there any other mechanism like $resource to call the REST service ? If yes, please share the code sample if I want to call above REST service.

Thanks in advance.

Jayanta Pramanik

















Naveen Kohli

unread,
Jul 6, 2014, 6:42:45 AM7/6/14
to ang...@googlegroups.com
You will pass data for POST in "data" property of http request.


The data you pass can be a single value, a json representation of object etc.
Message has been deleted

Jayanta Pramanik

unread,
Jul 6, 2014, 10:24:49 PM7/6/14
to ang...@googlegroups.com
Hi,

Thank you Naveen for your reply !
I sent data as you suggested but it is showing following errors. I tried it two ways without method name (fetchDetails) and with method name; in both cases I got similar error -

        $http({method: 'POST', url: 'http://localhost:8080/demoapp/service/GatewayService/fetchDetails/', data:acctno}).
                success(function(data, status, headers, config) {
                    alert("Success --------- !!!");
                    console.log("Success :"+data);
                  
                }).
                error(function(data, status, headers, config) {
                       //--- error message
                });

   ERROR found in Javascript Console in Chrome -

Failed to load resource: the server responded with a status of 404 (Not Found) http://localhost:8080/demoapp/service/GatewayService/fetchDetails/
XMLHttpRequest cannot load http://localhost:8080/demoapp/service/GatewayService/fetchDetails/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:63342' is therefore not allowed access. localhost:63342/angular-seed-master/app/newIndex.html#/videos/myaccount:1



Please tell me where I made mistake.

Regards,

Jayanta Pramanik
Reply all
Reply to author
Forward
0 new messages