44
© 2010 SpringSource, A division of VMware. All rights reserved © 2010 SpringSource, A division of VMware. All rights reserved Building Next-Gen Web Applications with the Spring 3.0 Web Stack Jeremy Grelle Senior Member Technical Staff SpringSource a division of VMware (a.k.a, Open Source Web Dude) (@jeremyg484) Friday, July 23, 2010

Building Next-Gen Web Applications with the Spring 3 Web Stack

Embed Size (px)

DESCRIPTION

 

Citation preview

Page 1: Building Next-Gen Web Applications with the Spring 3 Web Stack

© 2010 SpringSource, A division of VMware. All rights reserved© 2010 SpringSource, A division of VMware. All rights reserved

Building Next-Gen Web Applications with the Spring 3.0 Web Stack

Jeremy Grelle

Senior Member Technical Staff

SpringSource a division of VMware

(a.k.a, Open Source Web Dude)

(@jeremyg484)

Friday, July 23, 2010

Page 2: Building Next-Gen Web Applications with the Spring 3 Web Stack

2

Battling the rising complexity of web application development by building on a lightweight Spring foundation.

Friday, July 23, 2010

Page 3: Building Next-Gen Web Applications with the Spring 3 Web Stack

Next-Gen? - The Modern Web Dilemma

Web application requirement complexity continues to rise

• How do we manage this complexity?

• How do we expose our services to the largest possible audience?

• How do we give users the best possible experience in the shortest amount of time?

3

Friday, July 23, 2010

Page 4: Building Next-Gen Web Applications with the Spring 3 Web Stack

The Spring Web Stack - Simplicity and Power

The Spring Web Stack gives you:

• unified programming model

• multiple client types served with the same foundation

• adaptability - the right approach (i.e., stateless, stateful) for the given use case

4

Friday, July 23, 2010

Page 5: Building Next-Gen Web Applications with the Spring 3 Web Stack

5

The Spring Web Stack

Spring Framework and Spring MVC

SpringJavaScript

SpringWeb Flow

Spring Security

SpringBlazeDS Integration

Spring Faces

Friday, July 23, 2010

Page 6: Building Next-Gen Web Applications with the Spring 3 Web Stack

Web Stack Components

Spring Framework and Spring MVC• The foundation for all other components

Spring JavaScript• Ajax integration

Spring Web Flow• Framework for stateful web conversation

6

Friday, July 23, 2010

Page 7: Building Next-Gen Web Applications with the Spring 3 Web Stack

Web Stack Components (cont.)

Spring Security• Security framework

Spring Faces• Integration with JavaServer Faces via Web Flow

Spring BlazeDS Integration• Integration with Adobe Flex clients

7

Friday, July 23, 2010

Page 8: Building Next-Gen Web Applications with the Spring 3 Web Stack

CONFIDENTIALCONFIDENTIAL8

Next-Gen? - Productivity: More Important than Ever Before

Must resolve first obstacle to Java in the cloud

Expectations are higher than ever before

Success of Ruby on Rails et al has raised the bar for building simpler applications

Developer choice crucial in determining cloud• Cloud apps often new

• Often start simple

Java/JVM technologies perceived as complex

Friday, July 23, 2010

Page 9: Building Next-Gen Web Applications with the Spring 3 Web Stack

CONFIDENTIALCONFIDENTIAL9

Increasing Productivity: The Opinionation Pyramid

Grails/Roo

Spring

Servlet/other specifications

JVM

Ideal is to build on top of powerful, extensible layers

No need to move to introduce new runtime

Never hit a wall

Opinionated, Productive

Choice, Power

Friday, July 23, 2010

Page 10: Building Next-Gen Web Applications with the Spring 3 Web Stack

CONFIDENTIALCONFIDENTIAL10SpringOne 2GX 2009. All rights reserved. Do not distribute without permission.

The most popular rapid development framework for the JVM

Solutions built on solid foundations

Grails

Friday, July 23, 2010

Page 11: Building Next-Gen Web Applications with the Spring 3 Web Stack

CONFIDENTIALCONFIDENTIAL11

Spring Roo

Higher Java productivity

Familiar Java• Roo uses the Java APIs and standards you already

know and trust.

Usable and learnable• Roo features an extremely high level of usability and

an advanced shell

Trusted Spring Stack• Roo has no runtime – It’s just Spring

Easy Roo removal• Roo can be easily removed from a user project in

under five minutes.

Friday, July 23, 2010

Page 12: Building Next-Gen Web Applications with the Spring 3 Web Stack

12

Getting Started

Create a new Spring MVC project from a template• Most use Roo to do this, either from an IDE like STS or the command-line

Typical setup:

One DispatcherServlet registered in web.xml• FrontController that dispatches web requests to your application logic

• Generally the “default servlet” mapped to “/”

Two Spring Containers (or ApplicationContexts) instantiated• 1 “root” context to host “shared resources” required by Servlets / Filters

• 1 “web” context to host local application components delegated to by the DispatcherServlet• Your application components are typically discovered via classpath scanning

Friday, July 23, 2010

Page 13: Building Next-Gen Web Applications with the Spring 3 Web Stack

Demo

13

Friday, July 23, 2010

Page 14: Building Next-Gen Web Applications with the Spring 3 Web Stack

14

The Spring Web Stack

SpringJavaScript

SpringWeb Flow

Spring Security

SpringBlazeDS Integration

Spring Faces

Spring Framework and Spring MVC

Friday, July 23, 2010

Page 15: Building Next-Gen Web Applications with the Spring 3 Web Stack

Introduction to the MVC programming model

DispatcherServlet requests are mapped to @Controller methods • @RequestMapping annotation used to define mapping rules

• Method parameters used to obtain request input

• Method return values used to generate responses

Simplest possible @Controller:

15

@Controllerpublic class SimpleController {

@RequestMapping("/simple") public @ResponseBody String simple() { return "Hello world!"; }

}

Friday, July 23, 2010

Page 16: Building Next-Gen Web Applications with the Spring 3 Web Stack

Mapping Requests

By path• @RequestMapping(“path”)

By HTTP method• @RequestMapping(“path”, method=RequestMethod.GET)

• POST, PUT, DELETE, OPTIONS, and TRACE are are also supported

By presence of query parameter• @RequestMapping(“path”, method=RequestMethod.GET, params=”foo”)

• Negation also supported: params={ “foo”, “!bar” })

By presence of request header • @RequestMapping(“path”, header=”content-type=text/*”)

• Negation also supported

16

Friday, July 23, 2010

Page 17: Building Next-Gen Web Applications with the Spring 3 Web Stack

Mapping Requests (2)

Simplest possible @Controller revisited

17

@Controllerpublic class SimpleControllerRevisited {

@RequestMapping(value="/simple/revisited", method=RequestMethod.GET, headers="Accept=text/plain") public @ResponseBody String simple() { return "Hello world revisited!"; }

}

Friday, July 23, 2010

Page 18: Building Next-Gen Web Applications with the Spring 3 Web Stack

Request Mapping at the Class Level

@RequestMapping can be used at the class level• Concise way to map all requests within a path to a @Controller

18

@Controller@RequestMapping("/accounts/*")public class AccountsController { @RequestMapping("active") public @ResponseBody List<Account> active() { ... } @RequestMapping("inactive") public @ResponseBody List<Account> inactive() { ... }}

Friday, July 23, 2010

Page 19: Building Next-Gen Web Applications with the Spring 3 Web Stack

Obtaining Request Data

Obtain request data by declaring method arguments• A query parameter value

• @RequestParam(“name”)

• A group of query parameter values• A custom JavaBean with a getName()/setName() pair for each parameter

• A path element value• @PathVariable(“var”)

• A request header value• @RequestHeader(“name”)

• A cookie value• @CookieValue(“name”)

• The request body• @RequestBody

• The request body and any request header• HttpEntity<T>

19

Friday, July 23, 2010

Page 20: Building Next-Gen Web Applications with the Spring 3 Web Stack

Injecting Standard Objects

A number of “standard arguments” can also be injected • Simply declare the argument you need as a method param

HttpServletRequest (or its more portable WebRequest wrapper)

Principal

Locale

InputStream

Reader

HttpServletResponse

OutputStream

Writer

HttpSession

20

Friday, July 23, 2010

Page 21: Building Next-Gen Web Applications with the Spring 3 Web Stack

Validation

Trigger validation by marking a JavaBean parameter as @Valid• The JavaBean will be passed to a Validator for validation

• JSR-303 auto-configured if a provider is present on the classpath

Binding and validation errors can be trapped and introspected by declaring a BindingResult parameter• Must follow the JavaBean parameter in the method signature

• Errors automatically exported in the model when rendering views

• Not supported with other request parameter types (@RequestBody, etc)

21

Friday, July 23, 2010

Page 22: Building Next-Gen Web Applications with the Spring 3 Web Stack

Generating Responses

Return a POJO annotated with @ResponseBody• POJO marshaled as the body of the response

• Converted to a representation based on Accept header

• Default converters auto-configured for JSON, XML, Atom, etc

or

Return a logical view name• ViewResolver -> View layer kicks in

• View abstractions for numerous templating/rendering technologies (i.e., JSP, Tiles, Freemarker, Excel, PDF, Atom, JSON, XML)

• ContentNegotiatingViewResolver can chain ViewResolvers and select based on Accept header

or

Return a new ResponseEntity<T> object• More powerful, low-level; allows for setting custom response headers and status

22

Friday, July 23, 2010

Page 23: Building Next-Gen Web Applications with the Spring 3 Web Stack

Typical Controller Example

23

@RequestMapping("/hotels") public @ResponseBody List<Hotel> getHotels(@Valid SearchCriteria criteria) { return travelService.findHotels(criteria); }

@RequestMapping("/hotels/{id}") public @ResponseBody Hotel getHotel(@PathVariable Long id) { return travelService.findHotelById(id); }

@RequestMapping(value = "/hotels", method = RequestMethod.POST) public String addHotel(@Valid Hotel hotel) { hotel = travelService.addHotel(hotel); return "redirect:/hotels/" + hotel.getId(); }

HotelsController

Friday, July 23, 2010

Page 24: Building Next-Gen Web Applications with the Spring 3 Web Stack

Pluggability

Spring MVC allows you to customize just about any part of the request chain• HttpMessageConverters

• HandlerInterceptors

• ExceptionHandlers

• ViewResolvers

• HandlerMappings

• HandlerAdapters

• WebArgumentResolvers

• TypeConverters

• Validators

• ...and more

24

Friday, July 23, 2010

Page 25: Building Next-Gen Web Applications with the Spring 3 Web Stack

Demo

25

Friday, July 23, 2010

Page 26: Building Next-Gen Web Applications with the Spring 3 Web Stack

26

The Spring Web Stack

Spring Framework and Spring MVC

SpringWeb Flow

Spring Security

SpringBlazeDS Integration

Spring Faces

Spring JavaScript

Friday, July 23, 2010

Page 27: Building Next-Gen Web Applications with the Spring 3 Web Stack

Goals of Spring JavaScript

Encapsulate use of Dojo for common enterprise use cases• Ajax (fragment rendering support)

• Client-side validation

Promotes progressive enhancement• Robust in the face of JavaScript failure

• Maximizes potential audience

• Accessibility

27

Friday, July 23, 2010

Page 28: Building Next-Gen Web Applications with the Spring 3 Web Stack

Working with the Spring JavaScript API

Use API to apply decorations to HTML elements

Different types of decorations• WidgetDecoration

• AjaxEventDecoration

• ValidateAllDecoration

28

Friday, July 23, 2010

Page 29: Building Next-Gen Web Applications with the Spring 3 Web Stack

Ajax with Partial Rendering

29

<a id="moreResultsLink” href="search?q=${criteria.q}&page=${criteria.page+1}">

More Results

</a>

<script type="text/javascript">

Spring.addDecoration(new Spring.AjaxEventDecoration({

elementId: "moreResultsLink",

event: "onclick",

params: {

fragments: "searchResults”

}

}));

</script>

Name of tile to re-render on server

No callback function necessary to link in response

Friday, July 23, 2010

Page 30: Building Next-Gen Web Applications with the Spring 3 Web Stack

Form Validation

30

<form:input path="creditCard"/><script type="text/javascript"> Spring.addDecoration(new Spring.ElementDecoration({ elementId : "creditCard", widgetType : "dijit.form.ValidationTextBox", widgetAttrs : { required : true, invalidMessage : "A 16-digit number is required.", regExp : "[0-9]{16}” } }));</script>

Friday, July 23, 2010

Page 31: Building Next-Gen Web Applications with the Spring 3 Web Stack

Future of Spring JavaScript

Resource Handling and Partial Rendering ideas will be incorporated directly into Spring 3.1

Client-side bits will be incorporated into Spring Roo• Much better platform for realizing some of the original ideas (i.e., generation of

client-side validation based on Java model)• Can support multiple libraries through Spring Roo Addons

Will continue to support the API in Spring Web Flow releases

31

Friday, July 23, 2010

Page 32: Building Next-Gen Web Applications with the Spring 3 Web Stack

32

The Spring Web Stack

Spring Framework and Spring MVC

SpringJavaScript

Spring Security

SpringBlazeDS Integration

Spring Faces

SpringWeb Flow

Friday, July 23, 2010

Page 33: Building Next-Gen Web Applications with the Spring 3 Web Stack

Spring Web Flow

33

For implementing stateful flows• Reusable multi-step user dialogs

Plugs into Spring MVC

Spring Web Flow 2 available now• Incorporates lessons learned from 1.0

• Offers many new features

Friday, July 23, 2010

Page 34: Building Next-Gen Web Applications with the Spring 3 Web Stack

Web Flow Sweet Spot

34

Friday, July 23, 2010

Page 35: Building Next-Gen Web Applications with the Spring 3 Web Stack

New Web Flow 2 Features

• Ajax support• Partial page re-rendering in flow DSL

• Spring security integration

• Flow-managed persistence

• Convention-over-configuration• View rendering

• Data binding and validation

35

Friday, July 23, 2010

Page 36: Building Next-Gen Web Applications with the Spring 3 Web Stack

Spring Web Flow 3 - @Flow

• Extends @Controller model

• Define stateful UI flow control using plain Java

• Builds on Spring Web Flow infrastructure

36

Friday, July 23, 2010

Page 37: Building Next-Gen Web Applications with the Spring 3 Web Stack

@Flow Example

37

@Flowpublic class BookHotel {

private Booking booking;

@Autowired private transient BookingService booking;

public State start(@Input Long hotelId, Principal user) { booking = bookingService.createBooking(hotelId, user); return new EnterBookingDetails(); }

private class EnterBookingDetails extends ViewState { @Transition State next() { return new ReviewBooking() }; }

private class ReviewBooking extends ViewState {}

Friday, July 23, 2010

Page 38: Building Next-Gen Web Applications with the Spring 3 Web Stack

38

The Spring Web Stack

Spring Framework and Spring MVC

SpringJavaScript

SpringWeb Flow

Spring Security

Spring FacesSpring

BlazeDS Integration

Friday, July 23, 2010

Page 39: Building Next-Gen Web Applications with the Spring 3 Web Stack

Spring BlazeDS Integration

39

Spring’s Adobe Flex integration project

• Connects Flex clients to Spring-managed services• Using BlazeDS MessageBroker boot-strapped by Spring

• Makes Flex natural fit in a Spring environment• Uses Spring XML namespace for simplified setup

• Reduces the need for BlazeDS-specific config

Friday, July 23, 2010

Page 40: Building Next-Gen Web Applications with the Spring 3 Web Stack

Spring BlazeDS Integration

• Expose Spring beans as Remoting destinations (for RPC style interaction)• <flex:remoting-destination> or @RemotingDestination

• Message-style communication through native BlazeDS messaging, JMS, and Spring Integration channels• enables server-side push

• Integrate Spring Security to secure Flex apps• <flex:secured>

40

Friday, July 23, 2010

Page 41: Building Next-Gen Web Applications with the Spring 3 Web Stack

Demo

41

Friday, July 23, 2010

Page 42: Building Next-Gen Web Applications with the Spring 3 Web Stack

The Future

Other ideas being considered for Spring 3.1• Incorporation of Servlet 3.0 features (auto-config, async servlets, etc.)

• HTML5 support in the JSP tag library

• Offline caching support

• Cometd and WebSocket support

• Server-sent events

SpringOne 2010 in Chicago (www.springone2gx.com)• See lots more content on Spring Roo, Spring MVC, and deep-dives into mobile

and social integration

42

Friday, July 23, 2010

Page 44: Building Next-Gen Web Applications with the Spring 3 Web Stack

44

Thank you!

Friday, July 23, 2010