Develop a REST application using WildFly and AngularJS

This tutorial shows how you can build up an Enterprise application using REST Web services deployed on WildFly application server using as client the Javascript AngularJS library.

Let’s start building the server side at first. We will be using Maven to assemble the application that is engineered as a Web application including a REST service and an Entity class as model. The initial version of our service just contains a method to retrieve records using JPA:

@Stateless
@Path("/simple")
public class SimpleRESTService {

    @PersistenceContext
    EntityManager em;

    @GET
    @Path("/json")
    @Produces(MediaType.APPLICATION_JSON)
    public List<Person> getListJSON ()

    {
        Query query = em.createQuery("FROM Person");
        List<Person> customerList = query.getResultList();
        return customerList;
    }

 }

As you can see, the getListJSON returns a JSON formatted list of Person Entity. The Entity class is quite simple, containing two fields and one auto-generated id field:

@Entity
public class Person {
    public Person() {     }
 
    public Person(String name, String surname) {
        this.name = name;
        this.surname = surname;
    }

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Long id;
    private String name;
    private String surname;
    
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getSurname() {
        return surname;
    }
    public void setSurname(String surname) {
        this.surname = surname;
    }
}

Our REST application needs as well a JAX-RS Activator class which enables REST Services setting as base path “rest”:

@ApplicationPath("/rest")
public class JaxRsActivator extends Application {
}

Our server application is completed. You need the configuration file for JPA Persistence. To keep it simple, we will be using the default ExampleDS which ships with the application server. This file named persistence.xml needs to be included in the resources/META-INF folder of your project.

<persistence version="2.0"
   xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="
        http://java.sun.com/xml/ns/persistence
        http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
   <persistence-unit name="primary">
      <jta-data-source>java:jboss/datasources/ExampleDS</jta-data-source>
      <properties>
         <!-- Properties for Hibernate -->
         <property name="hibernate.hbm2ddl.auto" value="create-drop" />
         <property name="hibernate.show_sql" value="false" />
      </properties>
   </persistence-unit>
</persistence>

Finally, although not mandatory, we will include as well an import.sql file in the resources folder of your Maven application. This will create some initial data that can be displayed:

insert into person (id,name,surname) values (0,'john','lennon')
insert into person (id,name,surname) values (1,'ringo','starr') 
insert into person (id,name,surname) values (2,'paul','mccartney')

Now let’s move to the client side. We will be using two AngularJS libraries: angular.min.js and angular-resource.js :

<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular-resource.js"></script>
<script language="javascript">

      angular.module('myApp',['ngResource']);
            function Ctrl($scope,$resource) {
              var restservice = $resource(
              'http://localhost:8080/rest-angular/rest/simple/json', {     
               }, {
               query: { method: 'GET', isArray: true }
            }
          );
          $scope.objs = restservice.query();
         };

  </script>
</head>

<body>
    <div ng-app="myApp">
        <div ng-controller="Ctrl">
            <ul>
                <li ng-repeat="obj in objs">{{obj.name}} - {{obj.surname}}</li>
            </ul>
        </div>
    </div>
</body>
</html>

The scripting part of this application defines a module named ‘MyApp‘ which is dependent on ngResource. The $resource is an optional module which allow us to define object models, and in a descriptive manner, to specify:

  • The server-side URL for the resource
  • The types of parameters that are commonly seen for such requests
  • Some additional methods (you automatically get  get ,  save ,  query ,  remove , and delete for free) that encapsulate specific functionality
  • The expected types of responses (an array or an object)

The module MyApp is incapsulated in the Controller Ctrl that is referenced by the HTML div. Once that the REST service is invoked the data is included in the objs array that is iterated into the div section. By launching this page will display the two records that have been included in the import.sql script.

Filtering on the server side.

We will now add one more method to the REST Service which does a filter on the Person name:

    @GET
    @Path("/json/{name}")
    @Produces(MediaType.APPLICATION_JSON)

    public List<Person> getPersonByName(@PathParam("name") String name)

    {
        Query query = em.createQuery("FROM Person where name = :name");
        query.setParameter("name", name);
        List<Person> customerList = query.getResultList();
        return customerList;
    }

Now let’s see the changes required on the AngularJS side:

<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular-resource.js"></script>
<script language="javascript">

      angular.module('myApp',['ngResource']);
            function Ctrl($scope,$resource) {
              var restservice = $resource(
              'http://localhost:8080/rest-angular/rest/simple/json/:id', {     
               }, {
               query: { method: 'GET', isArray: true }
            }
          );
         
          
          $scope.search = function() {
              $scope.objs = restservice.query({ id: $scope.name });
           }
         };
         
  </script>
</head>

<body>
    <div ng-app="myApp">
        <div ng-controller="Ctrl">
            <button ng-click="search()">Search a name</button>
            <input type="text" ng-model="name" placeholder="name">
            <ul>
                <li ng-repeat="obj in objs">{{obj.name}} - {{obj.surname}}</li>
            </ul>
        </div>
    </div>
</body>
</html>

As you can see, we have simply added one parameter to the REST query (:name). This parameter is collected from the input text field that is bound to the “name” model and then passed to the REST query in the search function.
Here is the example in action:

Adding new Records

The last change we will add in the server side allow us to insert new records via a POST request. The data will come in JSON format so our method will both consume and produce JSON data:

    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public List<Person>  savePerson(String json) {
         JsonReader reader = Json.createReader(new StringReader(message));
         JsonObject obj = reader.readObject();
         String name = obj.getString("name");
         String surname = obj.getString("surname");
        
           em.persist(new Person(name,surname));
        
        return getPersonList ();
    }

As you can see, the parsing from JSON into Person object is done by the Java EE 7 JSON API and JsonReader/JsonObject objects. In the end, the method will return the updated list of Persons. From the client side we will add as well a POST method which invokes the REST Service:

<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular-resource.js"></script>
<script language="javascript">

      angular.module('myApp',['ngResource']);
            function Ctrl($scope,$resource) {
              var restservice = $resource(
              'http://localhost:8080/rest-angular/rest/simple', {     
               }, {
               query: { method: 'GET', isArray: true },
               create: { method: 'POST', isArray: true },
            }
          );        
          $scope.save = function() {
              $scope.objs = restservice.create({ name: $scope.name, surname: $scope.surname });
           }
         };


  </script>
</head>

<body>
    <div ng-app="myApp">
        <div ng-controller="Ctrl">
            <button ng-click="save()">Insert</button>
            <input type="text" ng-model="name" placeholder="name"> <input
                type="text" ng-model="surname" placeholder="surname">
            <ul>
                <li ng-repeat="obj in objs">{{obj.name}} - {{obj.surname}}</li>
            </ul>
        </div>
    </div>
</body>
</html>

The POST method is invoked from the save function as soon as the user clicks on the Insert button, passing the fields “name” and “surname” taken from the input text fields.

angularjs jboss wildfly

Hope you enjoyed this AngularJS –  WildFy tutorial. In the next one we will try to make it look a bit nicer by adding the ng-grid Javascript extension.