Angular JS and Bootstrap with Spring, Spring Security and Hibernate

Angular

Folks have been asking me if I knew of any good examples of a J2EE web application that utilizes the following technologies: Angular JS, Bootstrap, Spring 4, Spring Security 4 and Hibernate 5.2.4, and after searching around

I decided that it would be best to create an example project that would demonstrate the integration of all these technologies as well as describe some of the specifics.

Before you start

About this post:

  • 2 – 7 min average reading time
  • Suitable for beginner’s through to advanced

What you will gain reading this post:

  • A starter project ready for use
  • An overview of the technology choices for the starter project

What you can do to help support:

  • Like, comment and share this article
  • Follow this blog to receive notifications of new postings

Now, let’s get started.

Angular JS

Why choose this technology

For the example I wanted to create the client rich J2EE web application that uses a technology.

To utilize MVC on the client side allowing for a more responsive application and less server interactions.

To use a technology that is sort after on the market.

Technology focus areas

  • Angular JS
    • Directives
    • Routes
    • Template – Single Page Application (SPA)
    • Partials
    • Data binding
    • Filters & sorters
    • Controllers
    • Services
    • Http response interceptors are used to catch all 401 requests returned from the server and action them
    • Event broadcasting and on listeners.
    • Third-party library calls
  • Injection
  • Base64 encoding
  • Promises
  • Basic Authentication

Bootstrap

Why choose this technology

For the example I wanted to create the J2EE web application that looks professional and is quick to style.

Bootstrap is a responsive web library allowing for ideal UI displaying across different devices and resolutions.

Technology focus areas

  • Bootstrap
    • NavBar
    • Header
    • Dropdown
    • Panel
  • Responsive Web  Layouts

Spring 4.2.5

Why choose this technology

For the example I wanted to create the functionality scenarios to best emulate the industry best practices and for the reader to be able to walk away understanding how they can utilize the growing demand for a client rich front end while still  rely on the server side technologies that are currently strong in the market.

I decided to use Spring 4 MVC to create a RESTful API in which the client could GET, POST, PUT, DELETE data as it was required.

Technology focus areas

  • The initial Spring 4 configuration is done through XML, however this is purely to define certain features such as package scanning and to enable annotations.
  • Annotations are used and encouraged to configure your spring controllers, services, transactions, components etc.
  • RESTful entry points are defined through controllers and in turn they produce JSON responses.
  • CRUD operations.
  • Unit Test Support.

Spring Security 4.1.0

Why choose this technology

For the example I wanted to have the RESTful API endpoints protected as sensitive information can be accessed and sensitive operations performed.

Spring Security allows to have the endpoints annotated with @PreAuthorize, @Secured or @PostAuthorize depending on you configuration and when you want to have the security check performed.

Technology focus areas

  • Stateless
  • Annotations are encouraged to protect your RESTful endpoints, @PreAuthorize and @PostAuthorize annotations have been enabled @Secured has not
  • Basic Authentication
  • Token Authentication
  • An entry point that always returns http 401
  • Unit Test Support.

Hibernate 5.2.4

Why choose this technology

For the example I wanted to demonstrate a complete end to end solution where transaction operations could be executed that would show industry based standards.

Hibernate allows for JPA implementation utilizing the Entity Manager and creating simple transactions.

Technology focus areas

  • Connectivity Configuration via persistence.xml
  • JPA implementation via Spring Configuration.
  • HSQL In Memory Database for simplicity and no configuration requirements.
  • Unit Test Support.

Example

You can check out the project from the following location below:

Project URL: https://github.com/Rob-Leggett/angular_bootstrap_spring
Here is what you can learn:

  • Maven Modules
  • Gulp JS
  • Basic directives
  • Multiple views
  • Security
  • Filtering and sorting lists
  • Data Binding
  • Data retrieval via AJAX
  • Integration of client side MVC with server side MVC
  • Stateless API
  • RESTful entry points
  • Basic Authentication
  • Token Authentication
  • Data operations using JPA
  • In Memory Databases
  • Unit Tests
  • Integration Tests
  • Jasmine Tests

Did this help?

  • Like, comment and share this article
  • Follow this blog to receive notifications of new postings
  • View previous postings

43 thoughts on “Angular JS and Bootstrap with Spring, Spring Security and Hibernate

    1. Thanks for your query, since this is a maven application run mvn clean install to build the artifact and then you will need to deploy it to a web server, I recommend apache tomcat, this can be done stand alone or through an IDE, I may add an embedded jetty instance into the maven script later to run it but until then you need to deploy it.

  1. Thanks for this very interesting tutorial. I have some questions please 🙂 :

    – As a J2EE developer i wonder if, with angularjs, it’s the big time to get rid of mcv server side frameworks such as struts or jsf ?
    – How to use spring security taglibs with html pages in order to show or hide a section from a specific Role ?

    Many thanks for considering my request.

    1. Thank you very much for your kind words.

      In answer to your questions, I believe angularjs is not to remove mvc from the server side but enhance the experience, angularjs is a front end mvc framework which allow for a clean seperation of logical layers such as having services for your data calls, and logic as well as controllers to map the model between the view and back for your front end.
      On a side note take a good look at promises as well they allow for a then, catch and finally which is the equivelent for a java try, catch, finally make handling of error very simple.

      You cannot use the spring security tag libraries, they are tags that are java in the backend, the way to achieve this in angularjs would be to write a custom directive that would watch the user object that is in scope, based off the roles and the specified access role it would show the element in the dom, my suggestion would be to make it an attribute directive that would apply to the menu item such has: has-role=”somerole”

      Any other questions feel free to ask.

  2. Hi there
    Thanks for the nice example.

    I am having problem compiling the code

    [INFO] Error stacktraces are turned on.
    [INFO] Scanning for projects…
    [ERROR] The build could not read 1 project -> [Help 1]
    org.apache.maven.project.ProjectBuildingException: Some problems were encountered while processing the POMs:
    [ERROR] ‘build.plugins.plugin.version’ for com.github.klieber:phantomjs-maven-plugin must be a valid version but is ‘${phantomjs.maven.plugin.version}’. @ line 278, column

    at org.apache.maven.project.DefaultProjectBuilder.build(DefaultProjectBuilder.java:416)
    at org.apache.maven.DefaultMaven.collectProjects(DefaultMaven.java:663)
    at org.apache.maven.DefaultMaven.getProjectsForMavenReactor(DefaultMaven.java:654)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:243)
    at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:154)
    at org.apache.maven.cli.MavenCli.execute(MavenCli.java:582)
    at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:214)
    at org.apache.maven.cli.MavenCli.main(MavenCli.java:158)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)

    1. Sorry for the late reply, please check the pom properties and confirm that you have a version set for the maven plugin, the message is indicating that the value is not being injected.

  3. Thanks Robert so much, for this easy nice tutorial on angular-js and spring.

    A quick question: i was able to see the following html returned on chrome developer tools –> when the user enters the wrong password or username

    ********
    ErrorUnauthorized
    ********

    but in the index page or the template now showing?

  4. Robert,

    Is there a way to show on the log page the error messages returned when the user enters invalid password or username, currently the login page does not show any error when the user enters the wrong password/username?

    1. Sorry for the late response, from the angularjs code you would simply need to push the to errors array what you wanted, from the spring check out the UnauthorisedEntryPoint that returns the error for unauthorized access, you can check the AuthorisationException for specific conditions and return what error that you want, it is just important to remember to return a 401 as that is what the angular code is checking for.

  5. Hi Robert, just skimmed over you post and sounds interesting to me. Been having issues with combining Spring MVC, Hibernate and Spring Security all with a nice front end mvc such as angularjs. Most of the video tutorials work with Spring MVC, Security Hibernate/JPA with JSPs. Is there a video you have made of the process you followed, if not, would you be kind enough to consider doing one?
    Regards,
    Stans

    1. Thank you very much for the kind words.

      Unfortunately I do not have the time currently to make any video tutorials.

      Recommendations / Improvements are:
      – Use a IDE like IntelliJ, it has good support for angular.
      – Modular the application, you can have a parent and children api and ui.
      – When using maven I recommend having the api be built fully via maven, but for the ui module if using maven have it kick off a gulp build task to build your ui.

      This will give a much more versatile solution and is a better development practice.

      My current example is a very basic application and if I manage to get time will make and commit these changes myself to better help the community.

  6. Looks very promising and exactly the development stack I was looking for. I have been able to successfully build and deploy the api to tomcat 8 instance and manually deployed the client by extracting the zip file to a local apache server. However when I launch the client I am only getting a blank page. From what I can tell the index.html doesn’t contain the initial js calls to initialize angular load the partials. Is this correct? Did I miss a step or make some wrong assumptions along the way.

    1. Thank you for your feedback, and I am happy this is the stack you are looking for.
      1. The client needs to be on the root
      2. The gulp zip task will inject all the required js into the index.html, if you do view source on the index page do you see the all the js injected.
      3. In chrome push f12 to get to debug mode, push refresh and check the console, do you see console errors and 404s from the network tab.
      4. Cors is not enabled on the server so you will need to proxy the client via Apache so it appears on the same origin as the server.

      It should be working, but if not please let me know the error occurring or any findings you have.

      1. Got it. It was my apache configuration. Needed to create a virtual host, host entries, etc. Not to play with the proxy config for the api calls . Great work and thanks for your help again.

  7. i was unable to start the app( api and client) would you add a task that run the api side on jetty or tomcat and after that launch the client side with node ?
    thanks in advice

  8. when I am running the application using mvn clean install then I am getting following error

    Angular JS with Bootstrap and Spring Maven Webapp . SUCCESS [0.000s]
    [INFO] api ……………………………………….. SUCCESS [55.599s]
    [INFO] client …………………………………….. FAILURE [12.561s]
    [INFO] ————————————————————————
    [INFO] BUILD FAILURE

    Failed to execute goal com.github.eirslett:frontend-maven-plugin:0.0.20:gulp (gulp build) on project client: Failed to run task: ‘gulp –no-color’ failed. (error code 8) -> [Help 1]

    1. I have not had any issues with this, however I will checkout the code and see if I can replicate this. As a work around try to upgrade the frontend-maven-plugin to a greater version or run gulp from the command line.

    2. I have updated the pom to have the latest library versions, if you have trouble with the build delete the node_modules directory it creates under the client and then run mvn clean install. Thanks for your feedback.

  9. Thanks for your application code. It really help me understand and implement these new technologies.

    Why the login implementation is blank? Can we authenticate user from database password in this method?

    1. Thank you for your kind words. This example is using a database for authentication however I have configured it to use a In Memory database for this example to avoid work for people wanting to run the example, it uses Spring Security for the authentication and I recommend you refer to SecurityConfig as that is where the configuration is done for all authentication. If you wish to change the database it points to then modify persistence.xml.

  10. First, Thanks for the startup application it’s awesome.

    I deployed both client and api application correctely without any error, but I don’t know why the sign in page does just redirect to the main page and when i try to get the customers list, it bring a long list with empty data (if i disable the filter, otherwise it gives an error such as there is duplicated customers ),

    while log-in i didn’t got any error.
    I remarked that the controllers on the api doesn’t have the word “api” in the route so why we use it on the $http.get(..) on the authentificationService, and the second membre shouldn’t be the header witht the crypted data ? instead of null ? always on the login method of the same service

    as last question how does the application intialise the HSQDB with the script in the resources ?

    thank you

    1. Thank you for your kind words.

      I’ll try to answer you questions as best I can.

      1. The login page does not just redirect to the main page it navigates to the last accessed page excluding the login page, otherwise the default is the main page. To see this refer to listener.js.

      2. I am not sure why you would be getting a long list of empty values, that does not make much sense to me as the filter is only used to reduce results you and removing it should not effect the results you see except you won’t get less customers only all customers.

      3. The “/api” is part of the RequestMapping in the Spring Controller, I personally like to mark the controllers with that as the controllers are the API interface definition and it is clear to the client what it is calling.

      4. Not sure what you are referring to regarding the cryptic data and null, sorry.

      5. HSQL is configured in persistence.xml and the import.sql script in run on application startup.

  11. Thanks for the tutorial

    I am getting below error when i run client side. Can you please help me

    D:\ideaProjects\angular_bootstrap_spring-master\client>gulp
    [12:09:37] Requiring external module babel-register
    D:\ideaProjects\angular_bootstrap_spring-master\client\gulpfile.babel.js:3
    import gulp from ‘gulp’;
    ^^^^^^

    SyntaxError: Unexpected token import
    at exports.runInThisContext (vm.js:53:16)
    at Module._compile (module.js:387:25)
    at loader (D:\ideaProjects\angular_bootstrap_spring-master\client\node_modules\babel-register\lib\node.js:126:5)
    at Object.require.extensions.(anonymous function) [as .js] (D:\ideaProjects\angular_bootstrap_spring-master\client\node_modules\babel-register\lib\node.js:136:7)
    at Module.load (module.js:357:32)
    at Function.Module._load (module.js:314:12)
    at Module.require (module.js:367:17)
    at require (internal/module.js:16:19)
    at Liftoff.handleArguments (C:\Users\saleem.s\AppData\Roaming\npm\node_modules\gulp\bin\gulp.js:116:3)
    at Liftoff. (C:\Users\saleem.s\AppData\Roaming\npm\node_modules\gulp\node_modules\liftoff\index.js:193:16)

    1. Thank you for you comment, I believe this issue is related to running npm install babel and that installed version 6.5.2, however as of version 6 the usage of babel has changes, I have upgraded the project now to use version 6 and removed the need to run npm install babel and therfore removed this issue for yourself and others. Thank you for posting your finding, it was greatly appreciated.

  12. Thanks Robert for a nice tutorial.help me to run the application.
    I am able to set-up api, not able to do client.How to run gulp.babel.js.In my machine, node js already installed.So once client successfully run an gulp folder will be created under this angular_bootstrap_spring\client\node\node_modules

  13. Hello Robert,
    Thanks for the nice tutorial. It works like a charm. The only thing is that the user after a while can’t login anymore. I have to reboot my tomcat. Than it works again. What does ‘account_non_expired’, ‘account_non_locked’ and ‘credentials_non_expired’ means?
    What value must they have?

    1. Hi Roel,

      Thank you for your feedback, I have not experienced that before where Tomcat requires to be restarted, if I can replicate this I will address it.

      ‘account_non_expired’, ‘account_non_locked’ and ‘credentials_non_expired’ are ways that you can lock or expire a user account, these are good if you have a system that has payments and the payment has not been renewed then you can expire the account or if a user tries to log in say 5 times and fails you can lock the user account.

      Currently they should all be set to true.

      Thanks

      1. Hi Robert,
        Thanks for your quick response.
        The database fields are specified as bit(1). So has there be a 0 or a 1 in it to make the value true?

      2. It looks like the session expires and than the user can’t logon again. Nor other users can logon. Annoying.

  14. Please note that due to technical issues I had to close down my previous github account. I now have the exact same projects that my previous github account had now located at https://github.com/Rob-Leggett

    I am adding this comment as previous comments referring to my my old account and wanted to ensure anyone looking through the comments refers to my new github account.

    Thanks

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.