Java EE 7 with Angular JS – Part 1

Today’s post will show you how to build a very simple application using Java EE 7 and Angular JS. Before going there let me tell you a brief story:

I have to confess that I was never a big fan of Javascript, but I still remember the first time I have used it. I don’t remember the year exactly, but probably around mid 90’s. I had a page with 3 frames (yes frames! remember those? very popular around that time) and I wanted to reload 2 frames when I clicked a link on the 3rd frame. At the time, Javascript was used to do some fancy stuff on webpages, not every browser have Javascript support and some even required you to turn it on. Fast forwarding to today the landscaped changed dramatically. Javascript is a full development stack now and you can develop entire applications written only in Javascript. Unfortunately for me, sometimes I still think I’m back in the 90’s and don’t give enough credit to Javascript, so this is my attempt to get to know Javascript better.

Why Java EE 7?
Well, I like Java and the new Java EE version is pretty good. Less verbose and very fast using Wildfly or Glassfish. It provides you with a large set of specifications to suit your needs and it’s a standard in the Java world.

Why Angular JS?
I’m probably following the big hype around Angular here. Since I don’t have much experience with Javascript I don’t know the offers very well, so I’m just following advice of some friends and I have also noticed a big acceptance of Angular in the last Devoxx. Every room with an Angular talk was full, so I wanted to give it a try and found out for myself.

The Application

For the application, it’s a simple list with pagination and a REST service that feeds the list data. Every time I start a new enterprise project it’s usually the first thing we code: create a table, store some data and list some random data, so I think it’s appropriate.

The Setup

The Code (finally!)

Backend – Java EE 7

Starting with the backend, let’s define a very simple Entity class (some code is omitted for simplicity):

Person.java

Java

1

2

3

4

5

6

7

8

9

10

@Entity

publicclassPerson{

@Id

privateLongid;

privateStringname;

privateStringdescription;

}

If you’re not familiar with Java EE JPA specification, this will allow to model an object class into a database table by using the annotation @Entity to connect to the database table with the same name and the annotation @Id to identify the table primary key.

Two of my favourite new features on Java EE 7: now you can run sql in a standard way by using the properties javax.persistence.schema-generation.* and it also binds you to a default datasource if you don’t provide one. So for this case, it’s going to use the internal Wildfly H2 database for our application.

Finally, to provide the list data we need to query the database and expose it as a REST service:

The code is exactly as a normal Java POJO, but using the Java EE annotations to enhance the behaviour. @ApplicationPath("/resources") and @Path("persons") will expose the REST service at the url yourdomain/resources/persons, @GET marks the logic to be called by the http GET method and @Produces(MediaType.APPLICATION_JSON) formats the REST response as JSON format. Pretty cool with only a few annotations.

To make it a little easier to exchange the needed information for the paginated list, I have also created the following wrapper class:

PaginatedListWrapper.java

1

2

3

4

5

6

7

8

9

publicclassPaginatedListWrapper<T>{

privateIntegercurrentPage;

privateIntegerpageSize;

privateIntegertotalResults;

privateStringsortFields;

privateStringsortDirections;

privateList<T>list;

}

And we are done with the backend stuff.

UI – Angular JS

To display the data we are going to use Angular JS. Angular extends the traditional HTML with additional custom tag attributes to bind data represented in Javascript variables by following a MVC approach. So, lets look to our html page:

Apart from the Javascript and CSS declarations there is very little code in there. Very impressive. Angular also have a wide range of ready to use components, so I’m using the ng-grid to display the data and UI Bootstrap that provides a pagination component. The ng-grid also have a pagination component, but I liked the UI Bootstrap pagination component more.

There is something still missing. The Javascript file where everything happens:

person.js

JavaScript

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

varapp=angular.module('persons',['ngGrid','ui.bootstrap']);

// Create a controller with name personsList to bind to the html page.

app.controller('personsList',function($scope,$http){

// Makes the REST request to get the data to populate the grid.

$scope.refreshGrid=function(page){

$http({

url:'resources/persons',

method:'GET',

params:{

page:page,

sortFields:$scope.sortInfo.fields[0],

sortDirections:$scope.sortInfo.directions[0]

}

}).success(function(data){

$scope.persons=data;

});

};

// Do something when the grid is sorted.

// The grid throws the ngGridEventSorted that gets picked up here and assigns the sortInfo to the scope.

// This will allow to watch the sortInfo in the scope for changed and refresh the grid.

$scope.$on('ngGridEventSorted',function(event,sortInfo){

$scope.sortInfo=sortInfo;

});

// Watch the sortInfo variable. If changes are detected than we need to refresh the grid.

// This also works for the first page access, since we assign the initial sorting in the initialize section.

$scope.$watch('sortInfo',function(){

$scope.refreshGrid($scope.persons.currentPage);

},true);

// Initialize required information: sorting, the first page to show and the grid options.

$scope.sortInfo={fields:['id'],directions:['asc']};

$scope.persons={currentPage:1};

$scope.gridOptions={

data:'persons.list',

useExternalSorting:true,

sortInfo:$scope.sortInfo

};

});

The Javascript code is very clean and organised. Notice how everything gets added to an app controller, allowing you to have multiple separation of concerns on your business logic. To implement the required behaviour we just need to add a few functions to refresh the list by calling our REST service and monitor the grid data to refresh the view. This is the end result:

Resources

Update
In the meanwhile I have updated the original code with the post about Manage Javascript dependencies. Please, download the original source of this post from the release 1.0. You can also clone the repo, and checkout the tag from release 1.0 with the following command: git checkout 1.0.

I hope you enjoyed the post! Let me know if you have any comments about this.

Comments ( 98 )

nice start , i wish you should have used angular dart(https://angulardart.org/) instead of angular js, Angular dart based is based on dart (more structured lang like java) ,Java developer can pick this lang in hours .Personally i hate javascript

Hi Dave, thank your for your comment. What I meant was that there is no specification for the JSON Binding in Java EE 7, but it’s possible to do it and some technologies reuse the same JAXB annotations. I’m just not sure if when the new specification for JSON-B if the spec experts are going to add or reuse the same annotations.

Hi Chetan. Of couse. There is a link in the Resources section for my github repo with the full source, but maybe is not very visible. I changed that, but here is the link anyway: https://github.com/radcortez/javaee7-angular

Thanks a lot Roberto for this post .
I need to know if JSF can be combine with angularJS , because i have seen a post that provide informations about AngularFaces or something like this .And if it’s not possible to make this combination works , wath’s the alternative way to build some java ee application with angularJS and a java ee framework(Spring for example).

Hi Rsone. Thank you so much for your feedback. I don’t see any reason for it to not combine. but there might be a lot of work to integrate both technologies. I’m not familiar with the AngularFaces project, but seems like a start. Spring and Java EE are two different technologies, you can also mix the two, but what are you trying to accomplish exactly?

I am on a webapplication project. With that, I try to achieve combining JSF 2.1, AngularJS and using its REST-API.

Altough I have learnt JSF is not following REST-Architecture at all, I am trying to achieve invoking REST-calls to JSF via AngularJS-http-service.

Somehow, using those calls does not work if invoked within AngularJS, as I am getting the error that the server could not find the resource. Invoking those rest services within a browser by inputing the URL directly shows the desired information.

Thank you for your comment. I see no reason why it shouldn’t work. Without looking into the code its hard to diagnose the problem, but can you confirm that Angular is calling the correct URL for the REST service?

Nice example ,,
I have separated the front end from the back end.
The front end is a pure angularjs in http server and the back end is jax-rs in tomEE.
My question here is how to implement authentication and authorization here?
Please help me 🙂
Thanks in advance.
Hani

Thanks for this post. Im trying to start using rest with angular.
Your post is so good, but i have a doubt about architeture. Why you don’t use Spring MVC, I looked for this on the internet for diferences, vantages and disvantages between web rest applications using Spring MVC and not using , but i coudn’t find anything. Could you help about this doubt?

Hiii Roberto Cortez,
I wanted some kind of example in which we can insert fields value into database(mysql) by using angular js for example let us say i want to insert my user name and password into database,
kindly reply me with an example

Thank you very much for this very usefull article.
I have the following message when i try to add a person to the list:
“There was a problem with the server”.
I used a glassfish server with netbeans
I have the following error in the logs:
Internal Exception: java.sql.SQLSyntaxErrorException: La table/vue ‘PERSON’ n’existe pas.
Error Code: -1
Call: SELECT COUNT(ID) FROM PERSON
Query: ReportQuery(referenceClass=Person sql=”SELECT COUNT(ID) FROM PERSON”)
at org.eclipse.persistence.exceptions.DatabaseException.sqlException(DatabaseException.java:333)

The artical is really useful for learners.
I am deploying the appliction on JBoss6. And getting error that javax.naming.NameNotFoundException: PersonResource not bound
I am using mysql & cretaed datasource .I am able to connect to the database But not able to understand the issue
Please help

Yes, it’s possible. They are two separate technologies. It just happens that I was experimenting with Java EE 7 and I wanted to use the latest version. You shouldn’t have any problems using it with EE 6.

Hello , thank you very much , i’m beginner in java ee , when you say that in back-end you used : java ee 7 , you mean EJB and JPA ?
and front-end , you used HTML5 and angular JS because you separated back and front ? with API Rest
Please your answer will help me a lot ..

Yes, so EJB and JPA are just two specifications that belong to a wider API known as Java EE. I’ve also used JAX-RS specification to provide REST services. For the front-end I’ve used HTML, JS and Angular. All of the technologies reside in the same project

I am new to rest so I would like to know what the PaginatedListWrapper class does?
Also I would like to know how to authenticate in Java ee from angularjs and to have an session id between the both, can you point me in the right directon?

Thumbs up and a big thanks for your effort and time on the javee7-angular project , stumbled on it and I found it very useful for my current project at the uni; I’m working on building an online shop , using angular(frontend) and javee7(backend); have forked/cloned your project, built and deployed it on GlassFish and currently messing around with the code a little , u wld hopefully hear from me again soon

You could definitely create 2 projects, one for the Java EE side and another for the Angular side. These would separate your concerns and allow you to focus in one or another. The Angular project should be a Web Project.

Thanks for the sources and the tutorial !
My JEE was a bit rusty so the tutorial was a bit too fast on the backend part for me so the sources came in handy !

I tried to open your project using the NetBeans IDE. I can run the project and no error or warnings shows up. However, when the page opens up, the person list is empty, and I can’t save any new person…
When I try to save some new person, I have a “There was a problem in the server!” div that appears on top of the screen, but no error message.

I’ve seen that you are using the default data source, so I don’t understand what problems could show up… Any idea of what is the problem or even just a hint of what I could change in the code to have an actual error logged in the browser or server console so I could have more informations?

Aaaaaaand I now remember why I hated GlassFish in my school days… Apparently, this is a GlassFish 4.1.1 issue (GlassFish 4.1.1 was included in the JEE NetBeans bundle)

If anyone were to end up with this problem too, well, the only solution is to go back to Glassfish 4.1(.0) or maybe upgrade it to whatever is the current most recent version when you read this (though I most certainly can’t ensure you that it will work on said version)

Well, maybe I should also give WildFly a try, but that’s an adventure for another day…

Thanks Roberto, I was able to sort out those problems I had.
When I removed the datasource definition in my web.xml (made it empty) Websphere began to assign the default one and initialize the entityManager. Took me far too much time (days) to get to the bottom of it. With all the version/config changes it is a nightmare.
Also I needed to change DefaultValue(“id”) to DefaultValue(“p.id”) in PersonResource.listPersons to stop jpsql syntax from complaining with an exception.
Kind of you to share your work and ideas!
vj