In previous article, I have explained the concept of implementing restful web services with google GSON and Here in this article, I am following the same example code of previous article. So before reading this article please refer previous article. Now I am going explain AngularJS integration with restful web service. If you are new to restful web services, then learn it from the previous article. Here you need some basic idea on AngularJS. Observe the below image, there you can find AngularJS single page web application structure.

AJAX requests

Ajax requests such as POST and GET are important in implementing Restful web service. Here in this project, I have implemented POST and GET request methods. To understand these example you need to download case study project
index.html
This is the main file that user should load in the browser
app.js
This JS file contains all the the routing information
maintCtrl.js
This file contains main controller of the application. This controller will be loaded at the time of application loading.
UtilityFactories.js
This file contains util functions - HTTP Get and Post request methods.
home
Once you load index.html in browser, home.html, home.js will be loaded under ng-view div. This home page contains no controller logic, It contains two links for pageGet.html and pagePost.html  
pageGet
This folder contains HTML file pageGet.html, Controller file pageGet.js. Whenever user clicks on submit button, JS will trigger GET HTTP request and displays the output
pagePost
This folder contains HTML file pagePost.html, Controller file pagePost.js. Whenever user clicks on submit button, JS will trigger POST HTTP request and displays the output

Input and Output

Find below sample input and outputs

Input : http://localhost:8080/CaseStudyRestAngular/rest/employee/search?employeeId=2
Output :
{
   "employeeId":2
}

Input : http://localhost:8080/CaseStudyRestAngular/rest/employee/search?employeeName=2
Output :
{
   "employeeId":0,
   "employeeName":"2"
}

Input : http://localhost:8080/CaseStudyRestAngular/rest/employee/maintain
Input Data :
{
  "employeeId":5,
  "employeeName":"sri"
}
Output :
{
   "code":0,
   "message":"sri parsed successfully"
}

Get request

Get request takes only URL parameters and input. So we have to append the input to URL. Observe below code to know how angular process GET request
function (_url, success, error) {
    if (!_url) return false;
    var headerObj = {};
    headerObj = {
            'Accept': 'application/json'
    };
    $http({
            method: 'GET',
            url: _url,
            cache: false,
            xhrFields: {
                withCredentials: true
            },
            headers: headerObj
        })
        .success(function (data, status, headers, config) {
            if (status === 200) {
                success(data);
            } else {
                error(data);
            }

            return false;
        })
        .error(function (data, status, headers, config) {
            error(data);
            return false;
        });
}
Observe below java Rest Method. It takes version, employeeId and employeeName as input. So we should format the acceptable input for this method
@GET
@Path("search")
@Produces("application/json")
public String getEmployeeDetails(
            @DefaultValue("1") @QueryParam("version") int version,
            @QueryParam("employeeId") int employeeId,
            @QueryParam("employeeName") String employeeName){
}

Formating get request

http://localhost:8080/CaseStudyRestAngular/rest/employee/search?employeeId=2&version=1;
Here empleyeeId=2&version=1 is is the input.
Expected output :
{
   "employeeId":2
}

Post request in AngularJS

Post request send data to server in stream. This data was not attached to URL. Observe the below code of implementing POST request in AngularJS
function (_url, _reqData, success, error) {
    if (!_url) return false;
 
    var _modData = Object.keys(_reqData).map(function(k) {
        return encodeURIComponent(k) + '=' + encodeURIComponent(_reqData[k]);
    }).join('&');
 
    var headerObj = {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        'Api-Key':'test'
    };
    $http({
            method: "POST",
            url: _url,
            data: _modData,
            xhrFields: {
                withCredentials: true
            },
           headers: headerObj
        })
        .success(function (data, status, headers, config) {
            if (data && success) {
                success(data);
            }
            return false;
        })
        .error(function (data, status, headers, config) {
            $rootScope.openAlertModal("Error occured while hitting the service.");
            if (error) {
                error(data);
            }
            return false;
        });
}
Now observe the below java code of implementing POST REST method. Here inputData variable will have whole input data. So we have to send whole JSON string under input data.
@POST
@Path("maintain")
@Produces("application/json")
public String maintainEmployeeDetails(
    @DefaultValue("1") @QueryParam("version") int version,
    @FormParam("inputData") String inputData) {
}

Formating Data

Input JSON data
var emp = { "employeeId":5, "employeeName":"sri"}

Now attach "inputData"
{
 inputData:JSON.stringify(emp)
}

Now trigger the POST call with URL : http://localhost:8080/CaseStudyRestAngular/rest/employee/maintain

Expected output
{
   "code":0,
   "message":"sri parsed successfully"
}

0 comments:

Blogroll

Follow this blog by Email

Popular Posts