Develop a web application with AngularJS and Spring MVC

Nowadays customers have a rich web experience with Gmail, Google Apps, Facebook and Twitter. A basic server side rendered web pages doesn’t fit anymore to the new HMI (human-machine interface) needs.

AngularJs is one of the most successful front-end frameworks for RIA (Rich Internet Application Development) development.

AngularJs encourages the use of the Model-View-Controller (MVC) design pattern to decouple the code and to separate concerns.

   

Denver Art Museum / Daniel Libeskind

Despite the Javascript language specificities, a JEE developer will appreciate having some best practice and design patterns that he’s familiar with.

This article illustrate how to integrate AngularJs to a Spring MVC project. I hope this article will help developers to take the plunge and start using AngularJs.

The sample project source code is available on this link github.com/samer-abdelkafi/ng-project.
The sample IHM Demo is available here.

1. Add AngularJs librery

I adopted Webjars as a way to manage static web resources via the Maven dependency management mechanism. This could be done by front package manager like Bower.

<dependency>
    <groupId>org.webjars</groupId>
    <artifactId>angularjs</artifactId>
    <version>1.3.8</version>
</dependency>


Add ResourceHandler for webjars to your Spring configuration file if it isn’t already done.

@EnableWebMvc
@Configuration
@ComponentScan(basePackages = { "com.mycompany.myproject.web.controller" })
public class MvcConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
    // Non shown code
}

2. Develop the business logic

In this sample project, we have a simple business logic. The front-end get a list from a rest web service and display it.
The code bellow presents our business logic implementation.

Add a new javasvript file app.js.

angular
    .module('myApp', ['ngResource'])
    .service('UsersService', function ($log, $resource) {
        return {
            getAll: function () {
                var userResource = $resource('users', {}, {
                    query: {method: 'GET', params: {}, isArray: true}
                });
                return userResource.query();
            }
        }
    })
    .controller('UsersController', function ($scope, $log, UsersService) {
        $scope.users = UsersService.getAll();
    });

myApp : root module for the project.
UsersService : service for executing the http request
UsersController : controller executed when the page is loaded.

3. Develop the view part

AngularJs implements MVC pattern. The html page is the view part, the controller is developed client side by java script and the model is Json object to get from the server side.

Import AngularJs library to your Html code.

<!DOCTYPE html ng-app="myApp">
<html ng-controller="UsersController">
<!-- header code -->
<body>

<div ng-repeat="user in users">{{user.firstName}} {{user.familyName}}</div>

<script type="text/javascript" src="webjars/jquery/2.1.1/jquery.js"></script>
<script type="text/javascript" src="webjars/angularjs/1.3.8/angular.min.js"></script>
<script type="text/javascript" src="webjars/angularjs/1.3.8/angular-resource.min.js"></script>
</body>
</html>

4. Deploy and run the application

Now we will deploy and run the application to verify the configuration.

5. Application enhancement

5.1 Design enhancement

To enhance the application design, we use twitter bootstrap librery with a material design theme.

  • first step, add dependency for jquery, bootstrap and bootstrap-material-design using webjars.
  • Next, import css and js files to the html page.
  • finally, modify html code for displaying the list.

5.2 Functional enhancement

AngularJS comes with many handy filters built-in. We use “filter:string” to add search function. All strings or objects with string properties in array that match this string will be returned.

<!DOCTYPE html>
<html ng-app="myApp">
<head lang="en">
    <meta charset="UTF-8">
    <link rel="stylesheet" href="webjars/bootstrap/3.2.0/css/bootstrap.css">
    <link rel="stylesheet" href="webjars/bootstrap-material-design/0.2.1/css/material.css">
    <title></title>
</head>
<body ng-controller="UsersController">

<div class="row">
    <br>
    <div class="container">
        <div id="userList" class="col-sm-offset-1 col-sm-10">
            <div class="input-group">
                <input class="form-control" id="search" name="search" placeholder="Search for" ng-model="query"
                       required="required"/>
              <span class="input-group-btn">
                  <button type="submit" class="btn btn-default">
                      <i class="glyphicon glyphicon-search"></i>
                  </button>
              </span>
            </div>
            <div class="list-group">
                <div class="list-group-item">
                    <div ng-repeat="user in users | filter:query" class="list-group-item" style="margin-top:16px">
                        <div class="row-picture">
                            <img class="circle"
                                 src="http://i.forbesimg.com/media/lists/people/{{user.firstName | lowercase}}-{{user.familyName | lowercase}}_50x50.jpg"
                                 alt="icon">
                        </div>
                        <div class="row-content">
                            <h4 class="list-group-item-heading">{{user.firstName}} {{user.familyName}}</h4>

                            <p class="list-group-item-text"><i class="glyphicon glyphicon-envelope"></i> {{user.email}}
                            </p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<script type="text/javascript" src="webjars/jquery/2.1.1/jquery.js"></script>
<script type="text/javascript" src="webjars/angularjs/1.3.8/angular.min.js"></script>
<script type="text/javascript" src="webjars/angularjs/1.3.8/angular-resource.min.js"></script>
<script type="text/javascript" src="webjars/bootstrap-material-design/0.2.1/js/material.js"></script>
<script type="text/javascript" src="resources/js/app.js"></script>
</body>
</html>

The picture bellow presents a print screen for the application.

I think AngularJs, is one of the best front-end framework. It has many great features like data binding, dependency injection, MVC pattern implementation and page templates.

The major new version 2.0 of AngularJS has a significant deference from version 1.X, but it doesn’t seem to have migration path. AngularJs developers will encounter a drastically different looking framework and will need to learn a new architecture.

Even though there is no compatibility with the version 2.0, actual version has many good features and it’s still a good choice as a front-end framework.

20 thoughts on “Develop a web application with AngularJS and Spring MVC

  1. Le tuto est très intéressant Samer (waiting for more tutos).
    Question: comment Angular a pu savoir la page qui va être ouverte au lancement du projet?

  2. You’re welcome,

    AngularJs runs client side (in your browser). It’s imported by the index.html page.

    script type=”text/javascript” src=”webjars/angularjs/1.3.8/angular.min.js”

    Il this sample, he doesn’t need to look for any page. He just parses the current page.

  3. Could not autowire field: private org.springframework.data.jpa.repository.JpaRepository.

    Please advise.

  4. Nice post. But need the development flow of the application from scratch and it would be much more helpful. I got the whole code from GIT but was not able to create it from scratch. Thanks.

    1. Hi,
      The data.sql file is used for creating an embedded database.
      You can find the source code in the JPAConfig class.
      public DataSource dataSource() {
      return new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.HSQL).setName(“myDb”)
      .addScript(“classpath:schema.sql”).addScript(“classpath:data.sql”).build();
      }

      You can get the source code of the JPAConfig class here.
      https://github.com/samer-abdelkafi/ng-project/blob/master/src/main/java/com/mycompany/myproject/config/JPAConfig.java

    1. Webjars are front frameworks or library packaged in a jar file and they are loaded by maven as a dependency of your project.

      There is no directory for webjars. But if your run maven install, you will find them in a lib directory under:
      target// WEB-INF/lib/

Leave a comment