You are on page 1of 47

Spring MVC

It’s Time
Dror Bereznitsky
Senior Consultant and
Architect, AlphaCSP

Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar


2
Agenda

Introduction
Background
Features Review
– Configuration
– View technology
– Page flow
– Table sorting
– Search results pagination
– Validation
– AJAX
– Error handling
– I18n
– Documentation
Summary

Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar


3
Introduction

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

Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar


4
Introduction:: 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

Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar


5
Introduction:: More Key Features

Strong REST foundations


Data Binding Framework
Validation Framework
Internationalization Support
Tag Library

Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar


6
Introduction:: Full Stack Framework?

Spring MVC is not a full-stack web


framework, but provide the
foundations for such
Spring MVC is not opinionated
– You use the pieces you need
– You adopt the pieces in piece-meal
fashion

Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar


7
Introduction:: Spring 2.5

Released November 2007


Simplified, annotation based model
for developing Spring MVC applications
Less XML than previous versions
Focuses on
– ease of use
– smart defaults
– simplified programming model

Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar


8
Agenda

Introduction
Background
Features Review
– Configuration
– View technology
– Page flow
– Table sorting
– Search results pagination
– Validation
– AJAX
– Error handling
– I18n
– Documentation
Summary

Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar


9
Background:: 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

Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar


10
Background:: Request Handlers

Incoming requests are dispatched to


handlers
– There are potentially many handlers per
Dispatcher Servlet
– Controllers are request handlers

Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar


11
Background:: ModelAndView

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 View
The same Controller often returns
different ModelAndView objects
– To render different types of responses

Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar


12
Background:: Request Lifecycle

Handler

Copyright 2006, www.springframework.org

Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar


13
Features Review

Introduction
Background
Features Review
– Configuration
– View technology
– Page flow
– Table sorting
– Search results pagination
– Validation
– AJAX
– Error handling
– I18n
– Documentation
Summary

Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar


14
Features:: Configuration

Old school Spring beans XML


configuration
Annotation 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

Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar


15
Deploy a DispatcherServlet

Minimal web deployment descriptor


web.xml
<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> Dispatcher servlet configuration
</servlet>

Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar


16
Annotated Controllers

Simple POJO – no need to extend any


controller base class !
PhoneBookController.java
@Controller
public class PhoneBookController {

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


protected ModelAndView setupForm() throws Exception {
ModelAndView mv = new ModelAndView();

return mv;
}

Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar


17
Dispatcher Servlet Configuration

/WEB-INF/spring-mvc-demo.xml
– Setting up the dispatcher for annotation support
– Actually done by default for DispatcherServlet
<bean class=
"org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"/>

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

– Auto detection for @Controller annotated beans

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

Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar


18
Features:: View Technology

Supported out of the box:


– JSP / JSTL
– XML / XSLT
– Apache Velocity
– Freemarker
– Adobe PDF
– Microsoft Excel
– Jasper Reports

Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar


19
Configure 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>

Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar


20
Features:: Page Flow

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

Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar


21
Features:: 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.java

Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar


22
Page Flow – Step 1 Contd.

1
Handle GET
/demo/phoneBook

DispatcherServlet PhoneBookController

phoneBook

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

InternalResource
ViewResolver

Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar


23
Page Flow – Step 2

Choosing the view to be rendered


– Set the ModelAndView view name
@RequestMapping(value = "/phoneBook", method = RequestMethod.GET)
protected ModelAndView setupForm() throws Exception {
ModelAndView mv = new ModelAndView();
mv.setViewName("phoneBook");
return mv; PhoneBookController.java

– Or just return a view name String


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

Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar


24
Page Flow – Step 2 Contd.

1
Handle GET
/demo/phoneBook

DispatcherServlet PhoneBookController

phoneBook

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

InternalResource
ViewResolver

Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar


25
Features:: Sorting & Pagination

Sorting by column

Search results pagination

Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar


26
Features:: 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.jsp

Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar


27
Features:: 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

Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar


28
Features:: Form Binding

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>

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

Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar


29
Features:: 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

Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar


30
Bean Validation Configuration

Load validation XML configuration file [1]


Create a bean validator [2]

<bean id="configurationLoader"
class="DefaultXmlBeanValidationConfigurationLoader">
1
<property name="resource" value="WEB-INF/validation.xml" />
</bean>

<bean id="beanValidator"
class="org.springmodules.validation.bean.BeanValidator">
2
<property name="configurationLoader" ref="configurationLoader" />
</bean>

Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar


31
Bean Validation Configuration

Contact email validation


– Bound to the domain model and not to a
specific form
Domain
<validation> Model

<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> Validation.xml

Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar


32
Server Side Validations

Validator is injected to the controller


Reusing 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.java

Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar


33
Client 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>

Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar


34
Client Side Validation Contd.

Use Valang tag library to apply the


valang validator at client side
– Validation
<script expression
type="text/javascript" is translated to
id="contactValangValidator">
JavaScript
new ValangValidator('contact',true,new Array(
new ValangValidator.Rule('firstName','not implemented',
'Aturi="http://www.springmodules.org/tags/valang"
<%@ taglib least one field is required',function() { prefix="valang" %>
return ((! this.isBlank((this.getPropertyValue('firstName')), (null))) || (!
<script type="text/javascript" src="/scripts/valang_codebase.js"></script>
this.isBlank((this.getPropertyValue('department')), (null)))) || (!
this.isBlank((this.getPropertyValue('email')), (null)))})))
<form:form method="POST" action="/demo/phoneBook/list" id="contact"
</script>
name="contact" commandName="contact" >

<valang:validate commandName="contact" />


phoneBook.jsp

Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar


35
Features:: 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

Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar


36
AJAX:: Configuration

The department service Spring bean


<bean id="departmentServiceFacade" class=
"com.alphacsp.webFrameworksPlayoff.service.impl.
MockRemoteDepartmentServiceImpl“ />

Exposing it to JavaScript using DWR


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

Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar


37
AJAX:: 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.jsp

Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar


38
Features:: 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

Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar


39
Features:: I18n

LocaleResolver
– automatically resolve messages
using the client's locale
• AcceptHeaderLocaleResolver
• CookieLocaleResolver
• SessionLocaleResolver
LocaleChangeInterceptor
– change the locale in specific cases
Reloadable resource bundles

Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar


40
Features:: Documentation

Excellent reference documentation !


Books – mostly on the entire framework
Code samples
Many AppFuse QuickStart applications

Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar


41
Summary

Introduction
Background
Features Review
– Configuration
– View technology
– Page flow
– Table sorting
– Search results pagination
– Validation
– AJAX
– Error handling
– I18n
– Documentation
Summary
Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar
42
Summary:: 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

Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar


43
Summary:: Cons

Cons:
– Model2 MVC forces you to build
your application around
request/response principles
as dictated by HTTP
This 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

Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar


44
Summary:: 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

Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar


45
Summary:: References

http://springframework.org/
Spring Source
Spring Modules
Spring IDE
Appfuse light - spring MVC quickstarts
Matt Raible - Spring MVC
Expert Spring MVC and Web Flow

Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar


46
Thank
You !
Copyright AlphaCSP Israel 2008 – Web Framework Playoff Seminar
47

You might also like