In previous post, we have already seen Restful web services CRUD example. In this post, we will use AngularJS to call rest CRUD APIs. So we are going to create a view and then perform CRUD operations on the basis of button clicks.

Please change initParam “com.sun.jersey.config.property.package” property to provide correct controller package name if you are not using same package.

Create bean class

4) Create a bean name “Country.java” in org.arpit.java2blog.bean.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

packageorg.arpit.java2blog.bean;

publicclassCountry{

intid;

StringcountryName;

longpopulation;

publicCountry(){

super();

}

publicCountry(inti,StringcountryName,longpopulation){

super();

this.id=i;

this.countryName=countryName;

this.population=population;

}

publicintgetId(){

returnid;

}

publicvoidsetId(intid){

this.id=id;

}

publicStringgetCountryName(){

returncountryName;

}

publicvoidsetCountryName(StringcountryName){

this.countryName=countryName;

}

publiclonggetPopulation(){

returnpopulation;

}

publicvoidsetPopulation(longpopulation){

this.population=population;

}

}

Create Controller

5) Create a controller named “CountryController.java” in package org.arpit.java2blog.controller

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

packageorg.arpit.java2blog.controller;

import java.util.List;

import javax.ws.rs.DELETE;

import javax.ws.rs.GET;

import javax.ws.rs.POST;

import javax.ws.rs.PUT;

import javax.ws.rs.Path;

import javax.ws.rs.PathParam;

import javax.ws.rs.Produces;

import javax.ws.rs.core.MediaType;

import org.arpit.java2blog.bean.Country;

import org.arpit.java2blog.service.CountryService;

@Path("/countries")

publicclassCountryController{

CountryService countryService=newCountryService();

@GET

@Produces(MediaType.APPLICATION_JSON)

publicList getCountries()

{

List listOfCountries=countryService.getAllCountries();

returnlistOfCountries;

}

@GET

@Path("/{id}")

@Produces(MediaType.APPLICATION_JSON)

publicCountry getCountryById(@PathParam("id")intid)

{

returncountryService.getCountry(id);

}

@POST

@Produces(MediaType.APPLICATION_JSON)

publicCountry addCountry(Country country)

{

returncountryService.addCountry(country);

}

@PUT

@Produces(MediaType.APPLICATION_JSON)

publicCountry updateCountry(Country country)

{

returncountryService.updateCountry(country);

}

@DELETE

@Path("/{id}")

@Produces(MediaType.APPLICATION_JSON)

publicvoiddeleteCountry(@PathParam("id")intid)

{

countryService.deleteCountry(id);

}

}

@Path(/your_path_at_class_level) : Sets the path to base URL + /your_path_at_class_level. The base URL is based on your application name, the servlet and the URL pattern from the web.xml” configuration file.

@Produces(MediaType.APPLICATION_JSON[, more-types ]): @Produces defines which MIME type is delivered by a method annotated with @GET. In the example text (“text/json”) is produced.

Create Service class

6) Create a class CountryService.java in package org.arpit.java2blog.service
It is just a helper class which should be replaced by database implementation. It is not very well written class, it is just used for demonstration.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

packageorg.arpit.java2blog.service;

import java.util.ArrayList;

import java.util.HashMap;

import java.util.List;

import org.arpit.java2blog.bean.Country;

import org.arpit.java2blog.exception.CountryNotFoundException;

/*

* It is just a helper class which should be replaced by database implementation.

* It is not very well written class, it is just used for demonstration.

*/

publicclassCountryService{

staticHashMap<Integer,Country>countryIdMap=getCountryIdMap();

publicCountryService(){

super();

if(countryIdMap==null)

{

countryIdMap=newHashMap<Integer,Country>();

// Creating some object of countries while initializing

Country indiaCountry=newCountry(1,"India",10000);

Country chinaCountry=newCountry(4,"China",20000);

Country nepalCountry=newCountry(3,"Nepal",8000);

Country bhutanCountry=newCountry(2,"Bhutan",7000);

countryIdMap.put(1,indiaCountry);

countryIdMap.put(4,chinaCountry);

countryIdMap.put(3,nepalCountry);

countryIdMap.put(2,bhutanCountry);

}

}

publicList getAllCountries()

{

List countries=newArrayList(countryIdMap.values());

returncountries;

}

publicCountry getCountry(intid)

{

Country country=countryIdMap.get(id);

if(country==null)

{

thrownewCountryNotFoundException("Country with id "+id+" not found");

}

returncountry;

}

publicCountry addCountry(Country country)

{

country.setId(getMaxId()+1);

countryIdMap.put(country.getId(),country);

returncountry;

}

publicCountry updateCountry(Country country)

{

if(country.getId()<=0)

returnnull;

countryIdMap.put(country.getId(),country);

returncountry;

}

publicvoiddeleteCountry(intid)

{

countryIdMap.remove(id);

}

publicstaticHashMap<Integer,Country>getCountryIdMap(){

returncountryIdMap;

}

// Utility method to get max id

publicstaticintgetMaxId()

{intmax=0;

for(intid:countryIdMap.keySet()){

if(max<=id)

max=id;

}

returnmax;

}

}

AngularJS view

7) create angularJSCrudExample.html in WebContent folder with following content:

Explanation :

We have injected $http as we have done in ajax example through controller constructor.

1

2

3

4

5

6

7

app.controller("CountryController",function($scope,$http){

$scope.countries=[];

...

We have defined various methods depending on operations such as editCountry, deleteCountry, submitCountry

When you click on submit button on form, it actually calls POST or PUT depending on operation. If you click on edit and submit data then it will be put operation as it will be update on existing resource. If you directly submit data, then it will be POST operation to create new resource,

Every time you submit data, it calls refereshCountryData() to refresh country table below.

When you call $http, you need to pass method type and URL, it will call it according, You can either put absolute URL or relative URL with respect to context root of web application.

1

2

3

4

5

6

7

8

9

10

11

12

13

//HTTP GET- get all countries collection

function_refreshCountryData(){

$http({

method:'GET',

url:'http://localhost:8080/JAXRSJsonCRUDExample/rest/countries'

}).then(functionsuccessCallback(response){

$scope.countries=response.data;

},functionerrorCallback(response){

console.log(response.statusText);

});

}

8) It ‘s time to do maven build.

Right click on project -> Run as -> Maven build

9) Provide goals as clean install (given below) and click on run

Run the application

10) Right click on angularJSCrudExample.html -> run as -> run on server

Select apache tomcat and click on finish

10) You should be able to see below pageURL : “http://localhost:8080/AngularjsJAXRSCRUDExample/angularJSCrudExample.html”

Lets click on delete button corresponding to Nepal and you will see below screen:

Lets add new country France with population 15000

Click on submit and you will see below screen.

Now click on edit button corresponding to India and change population from 10000 to 100000.