@thspaeth
&

AngularJS and Spring

Bringing Single Page Applications
and Java Enterprise together

By Thorsten Spaeth
@thspaeth

Agenda

  1. Short introduction to common Java architectures and SPA
  2. What is AngularJS all about?
  3. Give me an example for all that buzz
  4. How about testing?
  5. Final thoughts

"What happened before on
Java and JavaScript..."

1. some basic JS-enabled components within JSF

<h:outputScript library="js" name="foobar.js"/>
				<h:commandButton onclick="showMessage();"/>

2. Generally possible in JSP

...but not really good at doing async XHR/AJAX

...and not easy, lean forward development

...hard to maintain for Frontend-Developers

Basics of JavaScript SPA
"world"

Client side state handling

What is different for a
Single Page Application

  • Communication between Client and server is mostly asynchronous and REST-based
  • Datatransfers are usually done via JSON
  • Client side code is accessible for all
  • Templating engine
  • State-Routing moved from server to client
  • Easy scaling
  • Ideally: Stateless server access

Loose Communication? Yes!

"Choose your menu"

(to only name a few...)

Get your hands dirty with AngularJS


What AngularJS provides

  • (Two way) data binding
  • Dependency Injection
  • inherited and isolated scopes for data
  • Directives
  • Client-side (form) validation
  • Filters (for tables etc.)
  • Application modules
  • HTTP-communication services
  • great 3rd party eco-system
  • ... and much more...

Under the hood

  • DOM-Model changes with jqLite
  • Over 1000 contributors as of AngularJs 1.3
    (jQuery: approx. 200 on github)
  • over 100 releases since the beginning in 2010
  • Google Trends: significant score for AngularJS

Under the hood

  • DOM-Model changes with jqLite
  • Over 1000 contributors as of AngularJs 1.3
    (jQuery: approx. 200 on github)
  • over 100 releases since the beginning in 2010
  • Google Trends: significant score for AngularJS

Common application structure

  • Javascript files separated by type or separation by functionality
  • All view templates are put into a separate folder
  • CSS
  • Libraries
  • Static resources (images, further resources)

Setup and installation

Are there any browser or system requirements?

Well...

Simple two way data binding example

DEMO

Full stack example with Spring

THE SPRINGBEER (DEMO)

Github: https://github.com/tspaeth/springxdemo
(http://goo.gl/WO1ufN)

Attr: http://en.wikipedia.org/wiki/Guinness#mediaviewer/File:Guinness.jpg

Full stack example with Spring

server side setup I

  • Spring Boot
  • Spring Data REST + Spring MVC backend
    • Example Services exposed
      • Login
      • get beer list
      • get beer details
      • add new beer
      • delete a beer

Spring Data REST access


 @RepositoryRestResource(path = "beer")
 public interface BeerRepository
   extends PagingAndSortingRepository<Beer, Long> {
     List<Beer> findByCompany(@Param("company") String companyName);
    }

  1. This resource is accessible via /beer
  2. returns a complete JSON-Object to the client

Spring Data REST response

Example call to http://localhost:8080/beer

    {
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/server/beer{?page,size,sort}",
      "templated" : true
    },
    "search" : {
      "href" : "http://localhost:8080/server/beer/search"
    }
  },
  "_embedded" : {
    "beers" : [ {
      "id" : 1,
      "brand" : "Becks",
      "comment" : "Bitter, but sweet and wild",
      "alcVol" : 5.1,
      "volume" : null,
      "companyLogoURL" : "",
      "_links" : {
        "self" : {
          "href" : "http://localhost:8080/server/beer/1"
        },
        "company" : {
          "href" : "http://localhost:8080/server/beer/1/company"
        },
        "ratings" : {
          "href" : "http://localhost:8080/server/beer/1/ratings"
        }
      }
    }...]
  },
  "page" : {
  "size" : 20,
  "totalElements" : 2,
  "totalPages" : 1,
  "number" : 0
  }
}
    

Custom Controller enhancements also work...

        
@Controller
public class CustomRatingController {
  @Autowired
  private RatingRepository ratingRepository;

  @RequestMapping("/beer/{beerId}/ratingsum")
  @ResponseBody
  Float getAverageRating(@PathVariable("beerId") Long beerId) {
    List<Rating> allRatingsForOneBeer = (List<Rating>)ratingRepository.findAllByBeerId(beerId);
    int sum = 0;
    int cnt = 0;
    for (Rating rating : allRatingsForOneBeer) {
      cnt++;
      sum = sum + rating.getScore();
  }
  Float average = (new Float(sum).floatValue() / new Float(cnt).floatValue());
  return average;
}
    

Full stack example with Spring

server side setup II

  • Spring Data JPA
    • H2 as Backend-DB
  • Spring Security
    • Form based login (for simplicity reasons)
    • Header-Token based access for users after login
    • X-Rest-Authentication: 28b8gki2g428ckq5hlq052k85u
    • HTTP error handling for access denied (401) and others

Full stack example with Spring

client side setup

  • AngularJS 1.3 "core"
  • Modules:
    • ui-router for state handling / routing
    • angular-translate for i18n
    • angular-local-storage for token storage

Essential AngularJS features

Directives

Directives

  • Directives are used for glueing AngularJS logic into the existing HTML-code
  • <!doctype html>
                 <html xmlns:ng="http://angularjs.org" id="ng-app"
                 ng-app="springbeer" lang="en">
                 <head>
    <div class="navbar-inner"
                ng-controller="MenuCtrl">
  • have and create (sub)scopes to communicate with the outer world
    ...scope: {
      'var1': '&',
      'var2': '=',
      'var3': '@'
    }
  • directive attribute style: data-my-directive or my-directive
  • non-data attributes will somehow break (X)HTML validation

Directives II

  • Directive structure
    • configuration information
    • link function
    • controller
    • template definition
  • access model data of the current scope with data binding expressions
    <input type="text" ng-model="beer.brand">
  • example for calling the table directive
    <div class="col-md-6">
      <div ui-grid="gridConfig" ui-grid-selection class="myGrid"></div>
    </div>
  • Further nice directives: ng-repeat, ng-if, ng-hide...

What are filters in AngularJS?

It's the Angular way to modify and filter existing model data

List model filter example

Filter input field:

<input type="text" ng-model="beerfilter">
Filtering:
<li ng-repeat="beer in beers | filter: beerfilter">
  <a ui-sref="details({'beerId': beer.id})">{{beer.brand}}</a>
  <img ng-src="{{beer.companyLogoURL}}">
</li>

Controllers & Views

Attr: http://commons.wikimedia.org/wiki/File:View_of_RAF_Coningsby_taken_through_a_top_turret_window_from_Tattershall_Castle_-_geograph.org.uk_-_1739872.jpg

Controllers & Views

  • Controllers define which data and functionality is bound per view or even only a DOM segment
  • Views show the model data being handed out from the controller and interact with function defined in the controllers
  • Multiple controllers per HTML document are quite common
  • They are bound together via the $scope object - the magic glue

Routing and routes

Attr: http://commons.wikimedia.org/wiki/File:Cycle_route_sign,_Downpatrick,_September_2009.JPG

Routings

  • Navigate between the page states
  • HTML5 mode (http://foobar.com/login) or
    Hashbang style URL (http://foobar.com/#/login)
  • Provide bookmarkable and reloadable URLs
  • Most important implementations
    • ng-resource by AngularJS-Team
    • ui-router by Rob Eisenberg (Angular 2 will include this)

ui-router example

angular.module('springbeer', ['ui.router'])
.config(function ($stateProvider,$urlRouterProvider) {
    $urlRouterProvider
        .otherwise('/');

    $stateProvider
        .state('home', {
        url: '/',
        templateUrl: 'views/home.html',
        controller: 'HomeCtrl'
        })
        .state('login', {
        url: '/login',
        templateUrl: 'views/login.html',
        controller: 'LoginCtrl'
})

Services, Factories, Events

Attr: http://commons.wikimedia.org/wiki/File:Tesla_auto_bots.jpg

Services & Factories & Providers

  • Commonly used (business) services for re-use in several controllers
  • Singletons, shared among all controllers within the current app/module
  • Different syntax definitions for each one of these three for different use cases

Example service &
event handling

 angular.module('springbeer').service('MessageService', ['...',
    function ($rootScope, $state) {
      var messages = {};
      $rootScope.$on(':error:denied', function (data) {
        messages.push('Your access has been denied. Please login');
        $state.go('login');
      })
    }]);

Network access & Promises

$http.get('http://mobeer.com/beer', config).success(
  function (response) {
    // do whatever you want to do in case of successful request
  }).error(function (err) {
    // Actions in case of HTTP-Error
  }
);

the essential $q service - or: Promise sugar

var deferredBeer = $http.get('http://mobeer.com/beer/'+$state.params.beerId);
var deferredRating = $http.get('http://mobeer.com/beer/'+$state.params.beerId + '/ratingsum');
$q.all([deferredBeer, deferredRating]).then(function (results) {
  $scope.beer = results[0].data;
  $scope.beer.rating = results[1].data;
})

The modular approach

AngularJS is capable to divide the application into modules

More AngularJS...

Other features you will get for free

Testing

http://commons.wikimedia.org/wiki/File:Medienerziehung_in_der_Schule.pdf

Jasmine or Protractor

  • Jasmine is a Javascript tool for executing unittests on Javascript code
  • Protractor is the AngularJS/Google way of executing Integration tests for AngularJS-applications
    • Uses WebDriver Protocol for Communication
    • Uses Selenium as the execution engine

Javascript eco system

  • Boilerplate AngularJS code templates
  • Node.JS npm package manager
  • Bower package manager
  • grunt / gulp build processors
  • Continuous integration with Travis CI
  • ... or even well-known Jenkins (with fingers crossed)

Summary

  1. AngularJS gives an easy ramp up to extend and enrich your current applications with a lot of SPA features
  2. The community has been exploding the last 2 years
  3. REST-abstraction gives a good layered Client-Server Java application
  4. Very usable for fast mocking / protoyping and agile projects
  5. Developers with different skill sets can be easy integrated into project roles for only frontend or only backend
  6. Pretty cool Chrome browser tools
  7. IntelliJ Webstorm provides really good IDE support

Future view on AngularJS 2.0

Rumors about incompatibilities and "incompatibilities"

The ongoing discussion is not substantial enough
to be serious in terms of project status

Demo project sources

You can find the sample code of the demo project at

http://goo.gl/WO1ufN

Further Information & basic learning resources

  • Nice presentation from ngeurope about "rebuilding AngularJS concepts from vanilla Javascript" @ https://www.youtube.com/watch?v=Mk2WwSxK218
  • Look at egghead.io video tutorials
  • Take a course at Pluralsight
  • ...or Google around - plenty of things to read

THANKS - MERCI - DANKE

Questions?

ts@conserata.com

Follow me on Twitter: @thspaeth