Agenda
Short introduction to common Java architectures and SPA
What is AngularJS all about?
Give me an example for all that buzz
How about testing?
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
One of the key features of SPA applications is the client side state handling.
This means that there won't be any intentional server calls in between page changes or click events on links if
handled correctly.
Therefore, only templates or if enabled some lazy loading mechanisms could be triggered.
So it is only some content that will be fetched from the server REST endpoints.
Even though with Composite Components / custom components you can do javascript also with JSF, it is more likely
hard to to an incremental and fast development.
What is different for aS ingle P age A pplication
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!
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
quite simple: Just download the angular.js
select additional modules you want to use
routing
internationalization
start developing
IDE-Support with Webstorm/Intellij IDEA
and also Eclipse (limited)
Are there any browser or system requirements?
Well...
Yes. AngularJS from 1.3 on will not officially support Internet Explorer 8 and earlier.
From what I really learned out of the last projects I was working on is: You can nearly find shims or modernizr
scripts for porting
features back to IE8. But at the end there is no guarantee it will always work and it is not officially
supported anymore.
Also Microsoft itself dropped all support on IE8 - so the strategy should be to enable a company to take a
modern browser instead of
fixing all the bad things in IE8 and earlier with a lot of effort.
- Chrome plays nicely with addons for Batarang, ng-inspector
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);
}
This resource is accessible via /beer
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
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
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
Factory has a factory function to return a service instance
Service has a constructor function and will internally be instanciated with new
Provider uses the $get syntax to create a service object - can be configured before instantiation
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
functional bundling
libraries
module might be called a container
You can see it as a bundle / like jar files
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
AngularJS gives an easy ramp up to extend and enrich your current applications with a lot of SPA features
The community has been exploding the last 2 years
REST-abstraction gives a good layered Client-Server Java application
Very usable for fast mocking / protoyping and agile projects
Developers with different skill sets can be easy integrated into project roles for only frontend or only backend
Pretty cool Chrome browser tools
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
The Angular team announced some radical changes it is thinking about earlier this year already and talked about
that on the ng-europe conference two weeks ago in Paris.
This caused a lot of discussions on the topics of stability and maintainability plus backwards compatibility of
AngularJS as a Javascript application framework for your favorite enterprise projects.
To be honest - nobody knows where and how the train will go to, but as AngularJS is intensively driven by the
community, I'm pretty sure that the whole system will find the right path sooner or later and how to cope with
the emerging changes. Most of them are necessary to provide an easy path for the future of HTML and
compatibility with ECMAscript 6.
So at the end, there will be no real smooth way to maintain all browsers out there.
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