integration of backbone.js with spring 3.1. agenda new features and enhancements in spring 3.1 what...

Post on 14-Jan-2016

344 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

INTEGRATION OF BACKBONE.JSWITH SPRING 3.1

AgendaNew Features and Enhancements

in Spring 3.1What is Backbone.js and why I

should use itSpring 3.1 and Backbone.js

integration by example

NEW FEATURES AND ENHANCEMENTS IN SPRING 3.1

New Features and EnhancementsCache AbstractionBean Definition ProfilesEnvironment AbstractionPropertySource AbstractionJava based-configurationSupport for Hibernate 4.xc: namespace for constructor

injectionSupport for injection against non-

standard JavaBeans setters

New Features and EnhancementsSupport for Servlet 3.0 code-based

configurationSupport for Servlet 3.0

MultipartResolverJPA EntityManagerFactory bootstraping

without persistence.xmlNew HandlerMethod-based Support

Classes For Annotated Controller Processing

"consumes" and "produces" conditions in @RequestMapping

New Features and EnhancementsFlash Attributes and

RedirectAttributesURI Template Variable

Enhancements@Valid On @RequestBody

Controller Method Arguments@RequestPart Annotation On

Controller Method ArgumentsUriComponentsBuilder and

UriComponents

Cache Abstraction

Spring 3.1 provides support for transparently adding caching into an existing Spring application similar to the transaction support.

@Cacheable("books")public Book findBook(ISBN isbn) {...}

Environment AbstractionUnifies access to profiles and properties from

different sources in single abstraction.

@Configuration

@PropertySource("classpath:db.properties")

public class PersistenceConfig {

@Autowired

private Environment env;

@Bean

public DataSource createDataSourceBean() {

DriverManagerDataSource dataSource = new DriverManagerDataSource();

dataSource.setDriverClassName(env.getProperty("db.driverClass"));

dataSource.setUrl(env.getProperty("db.url"));

dataSource.setUsername(env.getProperty("db.username"));

dataSource.setPassword(env.getProperty("db.password"));

return dataSource;

}

}

Servlet 3.0

No need for web.xml to bootstrap Spring 3.1 application.

public class MyWebAppInitializer

implements WebApplicationInitializer {

public void onStartup(ServletContext servletContext)

throws ServletException {

// Application context’s (root and dispatcher) goes

// here...

}

}

Bean Definition Profiles

Finally it is possible to define different set of components or different configuration for each environment (dev, test, production). Profiles may be defined via XML-configuration as well as Java-based config.

Profiles are activated via environment variables, JVM properties or servlet init-params.

Produces and consumesSince Spring 3.1 we can specify media-

type that is accepted and provided by mapped controller method. It is much more powerful than specifying Content-Type or Accept headers as used to do before.

@RequestMapping(method = POST, consumes = "application/json“, produces=“application/json”)

@ResponseStatus(CREATED)

@ResponseBody

public Task create(@RequestBody Task task) {

// ...

}

JSR-303 support for request bodyRequest body can be validated

using Bean Validation API

@RequestMapping(method = POST,

consumes = "application/json")

@ResponseStatus(CREATED)

@ResponseBody

public Task create(@Valid @RequestBody Task task) {

// No BindingResult in method signature

}

Exception Handlers

Now we can use @ResponseBody annotation on exception handlers:

@ExceptionHandler(MethodArgumentNotValidException.class)

@ResponseStatus(BAD_REQUEST)

@ResponseBody

public Notification onException(MethodArgumentNotValidException ex) {

FieldError error = ex.getBindingResult().getFieldError();

return new Notification(error.getField() + " " + error.getDefaultMessage());

}

Java based configuration

Get rid off XML hell. Spring 3.1 can be bootstrapped and configured entirely via Java with fallback to XML if necessary.

@Configuration

@EnableWebMvc

@ComponentScan(basePackages = "pl.consileon")

public class WebConfig {

// Bean configuration goes here...

}

BACKBONE.JS

What is this sorcery?Backbone.js gives structure to

web applications by providing models with key-value binding and custom events, collections with a rich API of enumerable functions, views with declarative event handling, and connects it all to your existing API over a RESTful JSON interface.

So why do I need Backbone.js?You’re building application with

lots of JavaScript providing great user experience.

You’re frontend is bunch of jQuery selectors and callbacks trying to keep in sync your UI and backend?

You’re convinced that backend shouldn’t care of rendering UI.

How Backbone.js works?The data is represented by

Model(s) and Collection(s), which are backed by server application.◦Models and Collections communicate

with backend API via REST interface with data formatted in Json

UI is represented by View(s).Router maps URL’s to appropriate

views.

Most importantViews do not render anything by

examining the Models attributes. Models and Collections notify appropriate Views about changes causing appropriate page fragments to re-render itself.

Each View represents logical part of a page and is backed by the Model or Collection.

HomeView (Tasks collection)

TaskView(Task)

The ‘el’ magicEach view is bound to some DOM

element accessible via ‘el’ attribute.The el attribute automatically narrows

the DOM that is searched via selectors◦Whenever attempt to access DOM element

via selector, the element is searched in DOM fragment scoped by ‘el’ not in whole page so there is no need for adding additional attributes uniquely identifying the element.

The ‘el’ attribute can be created from JavaScript templating library or bound to existing DOM element.

How to test it?http://pivotal.github.com/jasmine

/http://sinonjs.org/http://searls.github.com/jasmine-

maven-plugin/

DEMO

https://github.com/consileonpl/spring-3.1-backbone.js-todo-list

APIGET /tasks – list tasksPOST /tasks – create taskPUT /tasks/:id – update taskDELETE /tasks/:id – delete task

Q&A

top related