47

SpringMVC

  • Upload
    yuvalb

  • View
    13

  • Download
    0

Embed Size (px)

DESCRIPTION

Spring MVC by Dror Bereznitsky from AlphaCSP

Citation preview

Page 1: SpringMVC
Page 2: SpringMVC

Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar2

Spring MVCSpring MVC

Dror BereznitskySenior Consultant and

Architect, AlphaCSP

It’s TimeIt’s Time

Page 3: SpringMVC

Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar3

AgendaAgenda

IntroductionBackgroundFeatures Review– Configuration– View technology– Page flow– Table sorting– Search results pagination– Validation– AJAX– Error handling– I18n– Documentation

Summary

Page 4: SpringMVC

Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar4

IntroductionIntroduction

Spring’s web framework– Optional Spring framework component– Integrated with the Spring IoC container

Web MVC framework – Request-driven action framework– Designed around a central servlet– Easy for Struts users to adopt

Page 5: SpringMVC

Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar5

Introduction::Introduction:: Key Features Key Features

Simple model– Easy to get going - fast learning curve Designed for extension– Smart extension points put you in control

Strong integration– Integrates popular view technologies

A part of the Spring framework– All artifacts are testable and benefit from

dependency injection

Page 6: SpringMVC

Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar6

Introduction:: More Key FeaturesIntroduction:: More Key Features

Strong REST foundationsData Binding FrameworkValidation FrameworkInternationalization SupportTag Library

Page 7: SpringMVC

Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar7

Introduction:: Full Stack Framework?Introduction:: Full Stack Framework?

Spring MVC is not a full-stack web framework, but provide the foundations for suchSpring MVC is not opinionated– You use the pieces you need– You adopt the pieces in piece-meal

fashion

Page 8: SpringMVC

Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar8

Introduction:: Spring 2.5Introduction:: Spring 2.5

Released November 2007Simplified, annotation based model for developing Spring MVC applicationsLess XML than previous versionsFocuses on – ease of use– smart defaults– simplified programming model

Page 9: SpringMVC

Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar9

AgendaAgenda

IntroductionBackgroundFeatures Review– Configuration– View technology– Page flow– Table sorting– Search results pagination– Validation– AJAX– Error handling– I18n– Documentation

Summary

Page 10: SpringMVC

Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar10

Background::Background:: Dispatcher Servlet Dispatcher Servlet

Dispatcher Servlet - front controller that coordinates the processing of all requests– Dispatches requests to handlers

– Issues appropriate responses to clients

Analogous to a Struts Action Servlet

Define one per logical web application

Page 11: SpringMVC

Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar11

Background:: Request HandlersBackground:: Request Handlers

Incoming requests are dispatched to handlers– There are potentially many handlers per

Dispatcher Servlet– Controllers are request handlers

Page 12: SpringMVC

Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar12

Background:: Background:: ModelAndViewModelAndView

Controllers return a result object called a ModelAndView– Selects the view to render the response– Contains the data needed for rendering

Model = contract between the Controller and the ViewThe same Controller often returns different ModelAndView objects– To render different types of responses

Page 13: SpringMVC

Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar13

Background:: Request LifecycleBackground:: Request Lifecycle

Copyright 2006, www.springframework.org

Handler

Page 14: SpringMVC

Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar14

Features ReviewFeatures Review

IntroductionBackgroundFeatures Review– Configuration– View technology– Page flow– Table sorting– Search results pagination– Validation– AJAX– Error handling– I18n– Documentation

Summary

Page 15: SpringMVC

Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar15

Features:: ConfigurationFeatures:: Configuration

Old school Spring beans XML configurationAnnotation based configuration for Controllers (v2.5)– XML configuration is still required for

more advanced features: interceptors, view resolver, etc.

– Not mandatory, everything can still be done with XML

Page 16: SpringMVC

Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar16

Deploy a DispatcherServletDeploy a DispatcherServlet

Minimal web deployment descriptor

<servlet> <servlet-name>spring-mvc-demo</servlet-name> <servlet-class>

org.springframework.web.servlet.DispatcherServlet </servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value> /WEB-INF/spring-mvc-demo-servlet.xml </param-value> </init-param> </servlet>

Dispatcher servlet configuration

web.xmlweb.xml

Page 17: SpringMVC

Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar17

Annotated ControllersAnnotated Controllers

Simple POJO – no need to extend any controller base class !

@Controller

public class PhoneBookController {

@RequestMapping(value = "/phoneBook", method = RequestMethod.GET)

protected ModelAndView setupForm() throws Exception {

ModelAndView mv = new ModelAndView();

return mv;

}

PhoneBookController.javaPhoneBookController.java

Page 18: SpringMVC

Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar18

Dispatcher Servlet Dispatcher Servlet ConfigurationConfiguration

/WEB-INF/spring-mvc-demo.xml– Setting up the dispatcher for annotation support– Actually done by default for DispatcherServlet

– Auto detection for @Controller annotated beans

<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"/>

<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>

<context:component-scan base-package="com.alphacsp.webFrameworksPlayoff"/>

Page 19: SpringMVC

Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar19

Supported out of the box:– JSP / JSTL– XML / XSLT– Apache Velocity– Freemarker– Adobe PDF– Microsoft Excel– Jasper Reports

Features:: View TechnologyFeatures:: View Technology

Page 20: SpringMVC

Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar20

Configure the view technologyConfigure the view technology

View Resolvers – Renders the model– Decoupling the view technology JSTL view– JSP + JSTL –native choice for Spring MVC– Spring tag libraries

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view. JstlView “ /> <property name="prefix" value="/WEB-INF/views"/> <property name="suffix" value=".jsp"/></bean>

Page 21: SpringMVC

Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar21

Features:: Page FlowFeatures:: Page Flow

mv.setView(new RedirectView( "../phoneBook“ , true));

Page 22: SpringMVC

Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar22

Features:: Page Flow – Step 1Features:: Page Flow – Step 1

Mapping URLs to handler methods– Method level annotations– Can restrict to specific request method– URL strings can be error prone !

@RequestMapping(value = "/phoneBook", method = RequestMethod.GET) protected ModelAndView setupForm() throws Exception { ModelAndView mv = new ModelAndView(); mv.addObject("contacts", Collections.<Contact>emptyList()); mv.addObject("contact", new Contact()); … }

PhoneBookController.javaPhoneBookController.java

Page 23: SpringMVC

Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar23

Page Flow – Step 1 Contd.Page Flow – Step 1 Contd.

DispatcherServlet PhoneBookController

Handle GET /demo/phoneBook

1

InternalResourceViewResolver

2 phoneBook /WEB-INF/views/phoneBook.jsp

phoneBook

Page 24: SpringMVC

Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar24

Page Flow – Step 2Page Flow – Step 2

Choosing the view to be rendered– Set the ModelAndView view name

– Or just return a view name String

@RequestMapping(value = "/phoneBook", method = RequestMethod.GET)protected ModelAndView setupForm() throws Exception {

ModelAndView mv = new ModelAndView();mv.setViewName("phoneBook");return mv; PhoneBookController.javaPhoneBookController.java

@RequestMapping(value = "/phoneBook", method = RequestMethod.GET)protected ModelAndView setupForm() throws Exception { return " phoneBook "; }

Page 25: SpringMVC

Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar25

Page Flow – Step 2 Contd.Page Flow – Step 2 Contd.

DispatcherServlet PhoneBookController

Handle GET /demo/phoneBook

1

InternalResourceViewResolver

2 phoneBook /WEB-INF/views/phoneBook.jsp

phoneBook

Page 26: SpringMVC

Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar26

Features:: Sorting & PaginationFeatures:: Sorting & Pagination

Search results paginationSearch results pagination

Sorting by columnSorting by column

Page 27: SpringMVC

Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar27

Features:: Table SortingFeatures:: Table Sorting

Used the display tag library– Handles column display, sorting, paging,

cropping, grouping, exporting, and more– Supports internal and external sorting– Sort only visible records or the entire list

<%@ taglib uri="http://displaytag.sf.net" prefix="display" %>

<display:table name="contacts" class="grid" id="contacts" sort="list" pagesize="5" requestURI="/demo/phoneBook/list"> <display:column property="fullName" title="Name" class="grid" headerClass="grid" sortable="true"/> …</display:table> phoneBook.jspphoneBook.jsp

Page 28: SpringMVC

Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar28

Features:: Search Results PaginationFeatures:: Search Results Pagination

Used the display tag pagination support for the demo– Supports internal and external

pagination– Adds pagination parameter to request– Limited to HTTP GET

Page 29: SpringMVC

Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar29

Features:: Form BindingFeatures:: Form Binding

@ModelAttribute annotations

Spring’s form tag library– EL expressions for binding path

<td class="searchLabel"><b><label for="email">Email</label></b></td><td class="search"> <form:input id="email“ path="email" tabindex="2" /></td>

@RequestMapping(value = "/phoneBook/list")

protected ModelAndView onSubmit(

@ModelAttribute("contact") Contact contact, BindingResult result)

Page 30: SpringMVC

Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar30

Features:: ValidationsFeatures:: Validations

Used Spring Modules bean validation framework for server side validation– Clear separation of concerns– Declarative validation as in commons-

validation– Supports Valang - extensible expression

language for validation rules

Page 31: SpringMVC

Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar31

Bean Validation ConfigurationBean Validation Configuration

Load validation XML configuration file [1]Create a bean validator [2]

<bean id="configurationLoader"

class="DefaultXmlBeanValidationConfigurationLoader">

<property name="resource" value="WEB-INF/validation.xml" />

</bean>

<bean id="beanValidator"

class="org.springmodules.validation.bean.BeanValidator">

<property name="configurationLoader" ref="configurationLoader" />

</bean>

1

2

Page 32: SpringMVC

Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar32

<validation>

<class name="com.alphacsp.webFrameworksPlayoff. Contact "> <property name="email"> <email message="Please enter a valid email address"

apply-if="email IS NOT BLANK"/> </property> </class>

</validation>

Domain Model

Domain Model

Bean Validation ConfigurationBean Validation Configuration

Contact email validation– Bound to the domain model and not to a

specific form

Validation.xmlValidation.xml

Page 33: SpringMVC

Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar33

Server Side ValidationsServer Side Validations

Validator is injected to the controllerReusing the binding errors object

@Autowired Validator validator;

@RequestMapping(value = "/phoneBook/list") protected ModelAndView onSubmit(@ModelAttribute("contact") Contact

contact, BindingResult result) throws Exception { … validator.validate(contact, result); … PhoneBookController.javaPhoneBookController.java

Page 34: SpringMVC

Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar34

Client Side ValidationClient Side Validation

Valang validator – validation is defined in valang

expression language

<bean id="clientSideValidator"class="org.springmodules.validation.valang.ValangValidator">

<property name="valang"> <value> <![CDATA[ { firstName : ? IS NOT BLANK OR department IS NOT BLANK

OR email IS NOT BLANK : 'At least one field is required'} ]]> </value> </property></bean>

Page 35: SpringMVC

Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar35

<%@ taglib uri="http://www.springmodules.org/tags/valang" prefix="valang" %>

<script type="text/javascript" src="/scripts/valang_codebase.js"></script>

<form:form method="POST" action="/demo/phoneBook/list" id="contact" name="contact" commandName="contact" >

<valang:validate commandName="contact" />

Client Side Validation Contd.Client Side Validation Contd.

Use Valang tag library to apply the valang validator at client side– Validation expression is translated to

JavaScript<script type="text/javascript" id="contactValangValidator">

new ValangValidator('contact',true,new Array(

new ValangValidator.Rule('firstName','not implemented', 'At least one field is required',function() {

return ((! this.isBlank((this.getPropertyValue('firstName')), (null))) || (! this.isBlank((this.getPropertyValue('department')), (null)))) || (! this.isBlank((this.getPropertyValue('email')), (null)))})))

</script>

<script type="text/javascript" id="contactValangValidator">

new ValangValidator('contact',true,new Array(

new ValangValidator.Rule('firstName','not implemented', 'At least one field is required',function() {

return ((! this.isBlank((this.getPropertyValue('firstName')), (null))) || (! this.isBlank((this.getPropertyValue('department')), (null)))) || (! this.isBlank((this.getPropertyValue('email')), (null)))})))

</script>

phoneBook.jspphoneBook.jsp

Page 36: SpringMVC

Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar36

Features:: AJAXFeatures:: AJAX

No built in AJAX support– DWR is unofficially

recommended by Spring

Used DWR to expose the department service to JavaScript– Requires dealing for low-level AJAX– DWR has simple integration with Spring

Used script.aculo.us autocomplete component with DWR

Page 37: SpringMVC

Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar37

AJAX:: ConfigurationAJAX:: Configuration

The department service Spring bean

<dwr> <allow> <create creator="spring" javascript="DepartmentServiceFacade"> <param name="beanName" value="departmentServiceFacade"/> </create> </allow></dwr>

<bean id="departmentServiceFacade" class="com.alphacsp.webFrameworksPlayoff.service.impl.

MockRemoteDepartmentServiceImpl“ />

Exposing it to JavaScript using DWRDWR.xmlDWR.xml

Page 38: SpringMVC

Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar38

AJAX:: Autocomplete ComponentAJAX:: Autocomplete Component

<script type="text/javascript" src="/scripts/prototype/prototype.js"></script><script type="text/javascript" src="/scripts/script.aculo.us/controls.js"></script><script type="text/javascript" src="/scripts/autocomplete.js"></script>

<td class="search"> <form:input id="department" path="department" tabindex="3" cssClass="searchField"/> <div id="departmentList" class="auto_complete"></div> <script type="text/javascript">

new Autocompleter.DWR('department', 'departmentList', updateList, {valueSelector: nameValueSelector, partialChars: 0 });

</script></td>

phoneBook.jspphoneBook.jsp

Page 39: SpringMVC

Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar39

Features:: Error HandlingFeatures:: Error Handling

HandlerExceptionResolvers - handle unexpected exceptions– Programmatic exception handling– Information about what handler was

executing when the exception was thrown

– SimpleMappingExceptionResolver – map exception classes to views

Page 40: SpringMVC

Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar40

Features:: I18nFeatures:: I18n

LocaleResolver – automatically resolve messages

using the client's locale • AcceptHeaderLocaleResolver• CookieLocaleResolver• SessionLocaleResolver

LocaleChangeInterceptor– change the locale in specific cases

Reloadable resource bundles

Page 41: SpringMVC

Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar41

Features:: DocumentationFeatures:: Documentation

Excellent reference documentation !Books – mostly on the entire frameworkCode samplesMany AppFuse QuickStart applications

Page 42: SpringMVC

Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar42

SummarySummary

IntroductionBackgroundFeatures Review– Configuration– View technology– Page flow– Table sorting– Search results pagination– Validation– AJAX– Error handling– I18n– Documentation

Summary

Page 43: SpringMVC

Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar43

Summary:: ProsSummary:: Pros

Pros:– Highly flexible– Strong REST foundations – A wide choice of view technologies– New annotation configuration,

less XML, more defaults– Integrates with many common web

solutions– Easy adoption for Struts 1 users

Page 44: SpringMVC

Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar44

Summary:: ConsSummary:: Cons

Cons:– Model2 MVC forces you to build

your application around request/response principles as dictated by HTTPThis was done by design in Spring MVC

– Requires a lot of work in the presentation layer: JSP, Javascript, etc.

– No AJAX support out of the box– No components support

Page 45: SpringMVC

Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar45

Summary:: RoadmapSummary:: Roadmap

Spring 3.0 – August/September 2008– Unification in the programming model

between Spring Web Flow and Spring MVC• SpringFaces - JSF Integration• Spring JavaScript - abstraction over common

JavaScript toolkits• AJAX support• Conversational state

Page 46: SpringMVC

Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar46

Summary:: ReferencesSummary:: References

http://springframework.org/Spring SourceSpring ModulesSpring IDEAppfuse light - spring MVC quickstartsMatt Raible - Spring MVCExpert Spring MVC and Web Flow

Page 47: SpringMVC

Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar47

Thank Thank You !You !