Java EE 7 with Angular JS – Part 1

posted by Roberto Cortez on

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):

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.

Following by a persistence.xml:

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:

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:

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:

Java EE 7 - Angular - List

Next Steps:

For the following posts related with these series, I’m planning to:

Resources

You can clone a full working copy from my github repository and deploy it to Wildfly. You can find instructions there to deploy it. Should also work on Glassfish.

Java EE – Angular JS Source

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 ( 99 )

  1. Replychandu0101

    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

    if(“I am dumb ,are You also dumb?”) {
    alert(“Truth is broken!”);
    }

    and in NextSteps :
    I wish there is security added REST API’s 🙂

    • ReplyRoberto Cortez

      Don’t worry. I’m also planning to have something build in Dart 🙂

  2. ReplyTundeMichael

    Don’t you need to have the JAXB annotation @XmlRootElement on the entity for entity to JSON conversion?

    • ReplyRoberto Cortez

      Hi TundeMichael,

      JAXB is Binding for XML and does not include JSON. Actually, there is no equivalent no JAXB in Java EE 7, probably only in Java EE 8.

      Anyway, you don’t need the annotation to produce the JSON response in the REST service.

      • ReplyDave

        I think TundeMichael is correct, you need to have @XmlRootElement on your resource classes. JAXB annotations are used for JSON and XML.

        From Oracle’s own mouth:
        https://blogs.oracle.com/enterprisetechtips/entry/configuring_json_for_restful_web

        • ReplyDave

          Ok…played around a little more. So it’s not necessary in my simple test, but the JAXB annotations *do* pertain to JSON format.

          • Roberto Cortez

            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.

  3. Replychetan

    Hi Roberto,

    Could you provide the working demo of the above example?

    I am working on the same scenario of using angular-ui-bootstrap pagination with ng-grid, but that ain’t working.

    only the first,previous,next,last are displayed, no page numbers are displayed 🙁

    Thanks

  4. Replykacha

    Hi Roberto, thanks for this example. The pagination part does not work. Any hints?

    • Replykacha

      i tried now with your github repo and that works.

  5. ReplyViny Oliveira

    Awesome post man! Looking forward for the next one.

    • ReplyRoberto Cortez

      Thank you. I’m planning another one in the next couple of weeks.

  6. ReplyRsone

    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).

  7. ReplyRoberto Cortez

    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?

  8. Replymetao

    Hi
    I want to know how did you composed Node.js with JavaEE? This is cool if we do so.
    Thanks

    • ReplyRoberto Cortez

      Hi metao, Thank you for your comment. I’m not quite sure what do you mean with composed. Can you clarify me please?

  9. ReplyThomas Mundt

    Hi Roberto,

    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.

    Do you hava a clue?

    Yours, Tom

    • ReplyRoberto Cortez

      Hi Thomas,

      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?

      Cheers,
      Roberto

  10. Replyindy2005

    Hi,

    Whats the approach for testing the angular front end generally in this setup. I have an application using Spring, Spring Data Repositories and JAX-RS.

    The web application is bootstrapped in the usual way via web.xml to enable repository package scanning etc.

    But I am uncle unclear on how I would go about testing the Angular front end in what is not a pure javascript project?

    Any advice appreciated.

    Regards

    i

    • ReplyRoberto Cortez

      Hi indy2005,

      This is something that I’m going to write about in one of my following pots regarding Angular, but probably is better to mock your server side and focus only on the client.

      Is there any reason for you to have the Spring part up and running for the tests?

      Cheers,
      Roberto

  11. ReplyJameel Ahamed

    Hi Roberto Cortez, please send angular js frontend and java backend simple application. login controller and full single page application controller example pls send Roberto Cortez.

    • ReplyRoberto Cortez

      Hi Jameel,

      Can you tell me exactly what you need? What is missing from the example?

    • ReplyRoberto Cortez

      Hi Jameel,

      Can you tell me exactly what you need? What is missing from the example?

  12. ReplyJameel

    please send angular js front end and java backend more example send…please ERP application add.

    • ReplyRoberto Cortez

      Hi Jameel,

      I’ve been a bit busy, but expect another example soon.

  13. ReplySebastian Szlachetka

    Hi Roberto Cortez,

    You made my day! Thanks 🙂

  14. Replyhaniswe

    Hi Roberto

    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

  15. ReplyAlex

    Hi Roberto. Can I run this demo project with Tomcat? I have to create the H2 db?

    • ReplyRoberto Cortez

      Hi Alex,

      Thank you for reading!

      This sample doesn’t run on Tomcat. It uses features of Java EE 7, so you need Wildfly or Glassfish to run it.

  16. Replyhaniswe

    Thanks for your reply ..
    I have checked your link you gave me “the second one”
    http://www.butonic.de/2010/06/18/a-simple-jax-rs-security-context-example-in-glassfish/
    In the past I was working in the same style but I found basic Auth over SSL not secured enough and I really need to do it using Interceptor this example:
    http://www.developerscrappad.com/1814/java/java-ee/rest-jax-rs/java-ee-7-jax-rs-2-0-simple-rest-api-authentication-authorization-with-custom-http-header/
    but the problem is I don`t get it in somehow it is not clear ,, I really need some explanation or some source code to start with
    Again .. Thank you so much for helping us!!

    Kind Regards
    Hani

  17. ReplyHenrique

    Hi Rafael.

    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?

    Sorry, for my bad english, i’m brazilian.

    Thank’s a lot.

    • ReplyRoberto Cortez

      Hi Henrique,

      Your English is fine 🙂

      So, just to make sure I got your question right: Why use Angular instead of Spring MVC?

  18. Replywasim

    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

  19. ReplyTester

    Hi, good example, but I can`t connect to database? Where is database settings?

    Thank you

  20. ReplyMargaux

    Hi Roberto,

    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)

    Thanks for your help,

    Regards

    • ReplyRoberto Cortez

      Hi Margaux,

      Thank you very much for your feedback. Can you please tell me which version of Glassfish are you using?

      Cheers,

      • ReplyMargaux

        I’m using GlassFish Server 3.1.2.2

        • ReplyRoberto Cortez

          Hi Margaux,

          You need Glassfish 4 to run this sample.

          • Margaux

            Thanks for your help Roberto.

            Cheers,

          • Roberto Cortez

            No problem Margaux. Glad I could help.

            Cheers,

  21. ReplyPallavi

    Hi

    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

    • ReplyRoberto Cortez

      Hi Pallavi,

      Thank you so much for your feedback!

      Regarding your problem, I could use a stacktrace, but this sample only runs on Wildfly. I suspect that’s the problem.

      Cheers,

      • ReplyPallavi

        Thanks Roberto for the quick reply

        Actually curious to know any specific configuration that is used for Wildfly server, which can not be used for JBOss server?

        Thanks in advance
        Pallavi

        • ReplyRoberto Cortez

          Hi Pallavi,

          Yes, I’m using a few new features from Java EE 7 that are only supported in Wildly. For example the ability to load data in the persistence.xml file.

          Cheers,

  22. ReplyEleina

    Hello Robert,

    I really want to thank you for this post, it has been very helpful! I have one question: is it possible to use AngularJS with Java EE6?

    Thanks in advance!

    Eleina

    • ReplyRoberto Cortez

      Hi Eleina,

      Thank you very much for your feedback.

      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.

      Cheers,

      • ReplyEleina

        Hi Robert,

        All right thank you! I’ll give it a try! 🙂

        Regards

  23. Replypfcit

    Hi,

    Can I deploy angular.js on glassfish
    (doesnt seem to work when i deploy on bundled gf in netbeans)

    or do i need to use apache to serve up the index.html?

    Do i need any thing else to serve up angular?

    thx,
    paul

    • ReplyRoberto Cortez

      Hi Paul,

      You shouldn’t need anything else. Can you send me an error log?

      Cheers,
      Roberto

  24. Replykimosaki

    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 ..

    • ReplyRoberto Cortez

      Hi Kimosaki,

      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

      Cheers,

  25. ReplySudhir

    It looks like you used EJB. So to run this example, I must have to install an application server. right? I will not be able to run using Tomcat?

    • ReplyRoberto Cortez

      Hi Sudhir,

      Yes, but if you want to use Tomcat, you can use TomEE. It allows you to run Java EE in Tomcat.

  26. Replypradeep

    Many thanks for a very good tutorial. It helped me a lot to start using AngularJS without any problem.

    • ReplyRoberto Cortez

      Hi pradeep,

      Thank you so much for your positive feedback. Let me know if you need any further help.

      Cheers,
      Roberto

  27. ReplyBessem Hmidi

    Great article:) , consider the same example with https://bessemhmidi.github.io/AngularBeans/
    and give me your feedback 🙂 (that need a javaEE7 web profile server (it’s CDI a based framework))

    • ReplyRoberto Cortez

      Hi Bessem,

      Thank you very much for you feedback. I’ll have a look.

      I’m signed up for you JavaOne session, so we can meet each other there 🙂

  28. ReplyBessem Hmidi

    So, any feedback? (about angularBeans :))

    • ReplyRoberto Cortez

      Hi Bessem,

      I’ve been really busy, but I’m planning a new post about Angular, so hopefully I’ll get to check angularBeans 🙂

      Cheers,
      Roberto

  29. ReplyLuis

    Hello Mr. Cortez thanks for sharing this!!

    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?

    Thanks you very much!!

    Luis

  30. ReplyVarun

    This is amazing Roberto. I have never been fond of JS. I think Angular is a good way to start an afair with JS.

    • ReplyRoberto Cortez

      Hi Varun,

      Thank you for your comments. Hope you enjoy your work with JS 🙂

      Cheers,
      Roberto

  31. Replyjekuh

    Hello Roberto;

    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

    Cheers
    Jekuh

    • ReplyRoberto Cortez

      Hi Jekuh,

      Thank you for your feedback. I’m glad that the project helped you.

      I’m planning to add some more stuff to it. Not sure when, but hopefully soon.

      Cheers,
      Roberto

  32. ReplyFivalo

    Hi Roberto, Thank you for your post.

    I have a question. When I want to create a project with Angular and JEE Is it a good practice create two eclipse projects? and what kind of projects should I create specially to the Angular project.

    Thank you

    Fidel

    • ReplyRoberto Cortez

      Hi Fivalo,

      Thank you for your feedback.

      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.

      Cheers,
      Roberto

  33. ReplyZelarith

    Hi Roberto.

    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?

    Thanks !
    – Zelarith

    • ReplyZelarith

      Uh, actually, I do have errors in the browser console (bear with me, I’m not using my usual web browser !)
      Seems I get some code 500 – Internal error from the backend

    • ReplyZelarith

      So… I checked glassfish server console.
      I get a Warning logged that looks more like an error to me :

      “StandardWrapperValve[com.cortez.samples.javaee7angular.rest.PersonResource]: Servlet.service() for servlet com.cortez.samples.javaee7angular.rest.PersonResource threw exception
      java.lang.NoClassDefFoundError: Could not initialize class org.eclipse.persistence.jaxb.BeanValidationHelper
      at […] ”

      I get it once per call to the backend (so whenever I reload the page or try to save a new person)

    • ReplyZelarith

      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…

      Source : https://java.net/jira/browse/GLASSFISH-21440
      GlassFish archives : https://glassfish.java.net/download-archive.html
      How to add a server to Netbeans : https://docs.oracle.com/cd/E19798-01/821-1770/gioew/
      Then you just have to configure which server your projects runs on (right click on the project > properties > run > server)
      Hope this helps 🙂

      • ReplyRoberto Cortez

        Hi Zelarith,

        Thank you for your comments. I’m glad that you were able to fix your problem 🙂

        Let me know if you need anything!

        Cheers,
        Roberto

      • ReplyDmitry Smirnov

        The project runs successfully with Payara Server — the supported Glassfish fork.

        • ReplyRoberto Cortez

          Awesome! I’ve never tried it in Payara. Thanks for bringing this up!

  34. ReplySudadev

    Hello , thank you very much

  35. ReplyPhilip Lowney

    Hi Roberto, thank you for taking the time to this tutorial. We’re considering moving away from JSF towards Angular and this is very helpful 🙂 Thank you!

  36. Replyjava8

    how run this example

  37. Replymojtaba

    Hi, is there any sample for angular2

    • ReplyRoberto Cortez

      Unfortunately no. I guess I’ll have to work on that one 🙂

  38. Replyvj

    Roberto, It appears that my entitiyManager is null; do you have any idea why that might be so. I’m running on websphere 9.0. Thanks. VJ

    • ReplyRoberto Cortez

      I have no idea. Maybe some missing configuration for Websphere? Are you deploying the WAR as is?

  39. Replyvj

    Also your codeenvy link doesn’t take me to your project on codeenvy. cheers, VJ

    • ReplyRoberto Cortez

      It seems there is an issue with the account. I have to contact the Codenvy team to check it out. Thanks for noticing it.

  40. Replyvj

    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

  41. Replydavidnezan

    Incredible article Roberto! If you are looking for examples and projects have done in angular, take a look to my web .

    I’m interested in collaborate in any java or angular project.

    Contact me!

    Greetings,

    David

  42. ReplyReynaldo

    Hi there, this weekend is pleasant for me, because this occasion i am
    reading this great informative article here at my house.

Leave a Reply to Roberto Cortez Cancel reply

Your email address will not be published.

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>