Build Single Page Application with Java EE and AngularJS

The definition about Single Page Application (SPA) it was all the resources of HTML, CSS, and JavaScript is retrieved with a single page load and the appropriate resources are dynamically loaded and added to the page as necessary. SPA will reduce the amount of page refreshes which can be done with heavy usage of AJAX to communicate with the back-end (server side). This become popular lately, since with SPA you could maximize the audience of your software since it fit perfectly on both website and mobile environment.

I would like to show you about how to build a SPA with Java EE 7 as the back-end (server side) and AngularJS on the front-end (client-side). To be able following this tutorial you need to prepare JDK version 8 and Apache Maven for the back-end and on the front-end make sure you already have NPM, Bower, and GRUNT.

Before I started, I need to proclaim that most of my experience is with Java EE as back-end developer and I have a little experience with front-end. You could see that in this tutorial I’m still using AngularJS version 1 and with (maybe for some front-end developer) old tools such as Bower and GRUNT. What I want to share is about the big picture and how to developing SPA especially with Java EE, since there is very little resource if you try to looking building SPA with Java EE rather than using NodeJS or Python and I think the best tutorial building SPA with Java EE is come from Roberto Cortez.

Structure of the Project

You will build a SPA with theme of bookshop, the case was you need to separate between customer page and admin page which is for customer he or she can view all list of the books and for admin page you must create a page for creating, updating and listing all of the books. Of course for the sake of this tutorial I wouldn’t make a complex project rather than I will show you the basic of SPA with Java EE and AngularJS.

On this project, I would like to separate between back-end and front-end project. Back-end would require Java 8, Apache Maven, and application server such as Wildfly, Payara, Glashfish or TomEE. Like I said before, I don’t have many experience with front-end so this will using my latest knowledge to build the front-end using AngularJS 1, NPM, Bower and Grunt. For the sake of this tutorial, I will put both project under same git version control and it can be access on my github account.

PROJECT_HOME
|-- README.md
|-- Client
| |--- Gruntfile.js
| |--- assets
| |--- bower.json
| |--- index.html
| |--- package.json
| |--- src
| | |--- app.js
| | |--- controllers
| | |--- services
| | |--- directives
| |--- views
| | |--- templates
|-- Server
|--- pom.xml
|--- src

Back-End Project

Back-end project provided a REST which consumed by front-end, and you just need Java EE 7 to build a REST Web Service. Started with Java EE 7 Essentials Archetype you already have everything to build REST Web Service and just with this few lines of code to make sure you can use JAX-RS for making REST in Java EE 7.

@ApplicationPath("resources")
public class JAXRSConfiguration extends Application {
}

Since you will need a database to store the book, you will work with JPA. Let’s started write an entity class for the book.

Your bookshop have a circumstance that some of books price already include tax, but some of books not. So, you need to check if the books not include tax on the price you need to add the Tax since you don’t want to break a law, right?

Next, you need to write an EJB class to communicate with JPA to perform simple Create, Read, Update, and Delete (CRUD) action.

Finally, you could start writing a resources class to become your REST endpoint.

Ok, everything is done, with all of this sort of code your back-end is ready. Yes, of course I’m not mention about persistence.xml since it’s depend on what kind of database you will use, but if you want using default datasource for example H2 from Wildfly or Derby from Payara / Glassfish is still possible.

Java EE is very simple and make developer productive, and this is how your response and request json from back-end will be look like.

Front-End Project

Prerequisite in front-end project you need to have NPM, yes everything started with NPM then you can install bower with npm install -g bower and grunt with npm install -g grunt plus grunt-cli npm install -g grunt-cli. Actually NPM and bower have similarity in managing dependencies, but I more prefer flat hierarchy that bower provide so it’s just a matter of choice but in this tutorial I will show you how to use both NPM and bower.

Because you will made a different project, now you need to create your front-end project and everything can be started with npm init and bower init to create a file of package.json and bower.json.

package.json
bower.json

Building SPA is need a server to host and make sure the Angular worked, you could use http-server to run your SPA with embedded server but since you already have Java EE as the back-end you will used this. Grunt is have similarity like Apache Maven, as task runner you will have grunt to do concatenation for the JavaScript files, minify them and finally copy all the final front-end code into the back-end.

For your information, the back-end is just simple Java EE Web Archive so you need to put the front-end files on webapp directory and that is why you need Grunt to automate this repetitive task. I know some of you maybe heard about Yeoman, to build an Angular project easily but I want to show you how to build Angular project without any fancy tools so you will understand the basic.

Gruntfile.js

With this your SPA is almost completed, you just need to execute grunt build in front-end directory then move into your back-end directory to execute mvn clean install to build the war file and this is can be deploy into the application server, of course everything can be more simplified with IDE but I hope you grasp the basic concept.

Let’s started work on front-end code, first of all you need to create an index.html as the entry point of the SPA and of course to load all of our JavaScript and CSS files.

To navigate between state or you could say between pages, I’m choose Angular Route so you need to define the route provider in your Angular config.

Ok, now you will start to write some controller, services and directives to be able build your bookshop. First I will show you about AlertCtrl, just like you can see it’s defined on the index.html above. This controller responsible to retrieve a broadcast and then generate an alert depend on it’s success or error alert.

Working with REST it’s mean you do a lot of asynchronous call, in Angular there is $http which is already using Promise so your code will be look like this.

var books = $http.get('resources/books');
books.then(function(result) {
$scope.users = result.data
});

But, there is Angular Resource that will simplify your code, you just need to build a services for this Angular Resource like this.

Now, you don’t need to handle promise or anything and you can just write your code like this.

$scope.users = BookService.query();

I would like to give an example about how to perform simple cread, read, update and delete with Angular. First, you need to build a page that responsible to show list of all the resource data give some buttons for create new book, update book, and remove book.

Little explanation about something might be not familiar, <an-search> it’s a directive, just simple input tag to binding search filter on the table. <dir-paginate-controls> is a third party library for pagination with Angular, but the idea is same with ng-repeate but with advance feature to bring a pagination. That is all, and then now this is the controller for this page.

From controller above, I believe you could understand just read from the code right? I just give some explanation about extractSlug function that responsible to split the full URI from _links since you need the slug to retrieve single information. Next, about remove function which is success rather than reload the page (which is I usually do) to refresh the data you could broadcast an event to render again the table with new data.

Next, you need to made form page which is responsible in creating or updating the data.

This is the controller that responsible in creating and updating book resource.

Simple explanation about how to decide when to create a new resource or updating an existing resource is you could use a parameter on your URI, in this case I use slug since existing resource must have slug.

Finally, this is the bare minimum tutorial of building a SPA with Java EE and AngularJS. Well, it’s become longer than I expected (I know I should split it) but on this story I just want to show you that Java EE is possible in building modern website, it’s not inferior from another programming language for example like Ruby or Nodejs.

If you enjoyed reading this article, please recommend with click the 👏 below and share it to help others find it!

References: