SlideShare una empresa de Scribd logo
1 de 18
Descargar para leer sin conexión
Spring MVC

 Richard Paul
Kiwiplan NZ Ltd
 27 Mar 2009
What is Spring MVC

Spring MVC is the web component of Spring's framework.

Model - The data required for the request.
View - Displays the page using the model.
Controller - Handles the request, generates the model.
Front Controller Pattern
Controller Interface

public class MyController implements Controller {
  public ModelAndView handleRequest(
      HttpServletRequest request,
      HttpServletResponse response) {

        // Controller logic goes here
    }
}


This is the low level interface for controllers, most of the time you will not use
the Controller interface directly.

The ModelAndView, is an object that holds the model objects as well as the
view required to be rendered (simplified definition).
Controller Annotations

@Controller
public class ItemController {

    private ItemService itemService;
    @Autowired
    public ItemController(ItemService itemService) {
      this.itemService = itemService;
    }

    @RequestMapping(value=quot;viewItem.htmquot;, method=RequestMethod.GET)
    public Item viewItem(@RequestParam Long id) {
      return itemService.get(id);
    }

}

By convention a view with the name 'viewItem' (based on the request mapping URL) will be
used to render the item.
Session attributes

@Controller
@RequestMapping(quot;editItem.htmquot;)
@SessionAttribute(quot;itemquot;)
public class ItemEditorController {

    @RequestMapping(method=RequestMethod.GET)
    public String setupForm(@RequestParam Long itemId, ModelMap model) {
      Item item = ...; // Fetch item to edit
      model.addAttribute(quot;itemquot;, item);
      return quot;itemFormquot;;
    }

    @RequestMapping(method=RequestMethod.POST)
    public String processSubmit(@ModelAttribute(quot;itemquot;) Item item) {
      // Store item
      // ...
      return quot;redirect:/viewItem.htm?item=quot; + item.getId();
    }
}

A GET to 'editItem.htm' adds the item with the given ID to the user's session. When a POST is made, this
item is pulled from the session and provided as an argument to the processSubmit method.
Flexible Method Arguments

Methods mapped with @RequestMapping can have very
flexible method signatures.
Arguments
handle(@RequestParam Long id) // 'id' parameter from request
handle(@ModelAttribute Item item, BindingResult result)
handle(ModelMap modelMap) // The model to populate
handle(HttpSession session) // The user's session
handle(Locale locale) // The locale (from the locale resolver)

Return Type
String // View name
ModelAndView // Model objects and view name
Item // Or other object, assumed to be the model object
void // This method handles writing to the response itself

http://static.springframework.org/spring/docs/2.5.x/reference/mvc.html#mvc-ann-
requestmapping-arguments
Testability

We no longer need to pass in a HttpServletRequest when unit
testing controllers. Most use cases can simply pass objects
into the method. Examples show with Mockito.

public Item view(@RequestParam Long id) {
  return itemService.get(id);
}

@Test
public void viewWithValidId() {
  Item item = new Item(3l);
  when(itemService.get(3l)).thenReturn(item);
  assertEquals(item, controller.view(3l));
}
Testability - with model attributes

public String submitItem(@ModelAttribute Item item) {
  itemService.save(item);
}

@Test
public void submitItem() {
  Item item = new Item(3l);
  controller.submitItem(item);
  verify(itemService.save(item));
}

Previously the item would have been manually placed into a
mock session under the 'item' key before calling the test.
Binding

In order to bind request parameters to Java objects, Spring
uses PropertyEditors.

Default Property Editors
                           // For Strings
ByteArrayPropertyEditor
                           // For numbers, e.g. 4, 3.2
CustomNumberEditor
...

Spring Provided Editors
                           // For whitespace trimmed Strings
StringTrimmerEditor
                           // For file uploads
FileEditor
...

Custom property editors can be written.
e.g. CategoryPropertyEditor for binding a Category.
Example - CategoryPropertyEditor

public class CategoryPropertyEditor extends PropertyEditorSupport {
  @Override
  public String getAsText() {
    Object value = getValue();
    if (value == null) {
      return quot;quot;;
    }
    return ((Category) value).getId().toString();
  }
  @Override
  public void setAsText(String text) {
    this.setValue(null); // Always clear existing value
    if (!StringUtils.isBlank(text)) {
      long id = Long.parseLong(text);
      this.setValue(categoryService.get(id));
    }
  }
}

If an IllegalArgumentException is thown a binding error is stored and can be
shown against the field in the form.
Registering Property Editors

Those property editors that aren't automatically wired up need
to be initialised against the DataBinder.

@InitBinder
public void initBinder(DataBinder binder) {
  // Register a new editor each time as they are not thread safe
  binder.registerCustomEditor(
    Category.class, new CategoryPropertyEditor());
}
Validation

Spring provides a validation framework that is usually invoked
in the controller layer.

Also possible to register different editors based on the field.

An alternative, which is still in draft form is JSR-303. It provides
validation at a model level and can be used in the presentation,
business & persistence layers.
Example - ItemValidator

Spring validator example.

public class ItemValidator implements Validator {

    public boolean supports(Class clazz) {
      return Item.class.isAssignableFrom(clazz);
    }

    public void validate(Object target, Errors errors) {
      Item item = (Item) target;
      ValidationUtils.rejectIfEmpty(e, quot;namequot;, quot;name.emptyquot;);
      if (item.getCategory() == null) {
        e.rejectValue(quot;categoryquot;, quot;item.category.requiredquot;);
      }
    }
}

Errors are stored in the Errors object, if any errors are present, the form can be
redisplayed with error messages instead of following the normal form submission.
Views

Spring supports a number of view technologies, the below
example shows JSP with JSTL, specifically Spring's Form tags.
<form:form method=quot;postquot; commandName=quot;itemquot;>
  <form:label path=quot;namequot;>Name</form:label>
  <form:input path=quot;namequot;/>
  <!-- Binding & Validation errors displayed here -->
  <form:error path=quot;namequot; cssClass=quot;errorquot;/>

  <!-- Show a select list of categories. Categories already set
       on the item are automatically selected -->
  <form:select path=quot;categoriesquot; items=quot;${allCategories}quot;
    itemValue=quot;idquot; itemLabel=quot;namequot;/>

</form:form>

Form tags are include for all HTML input types, e.g. form:radio, form:textarea
Resolving Messages

Spring resolves all messages using MessageSource interface.

This message source is uses dot notation to access message
coes. e.g. item.name.required

Using springs default MessageSource, properties files using a
specific locale are used.
ApplicationResources.properties      // Fall back
ApplicationResources_en.properties   // English
ApplicationResources_es.properties   // Spanish


Custom implementations of MessageSource can be
written. Useful if messages are pulled from a different backend
e.g. XML
AJAX Support

AJAX support is limited in Spring 2.5

Generally use a separate library to generate JSON data for the
controller to return.

Hopefully better support will be coming with Spring 3.0 with
new view types for XML, JSON, etc.
Questions?




Spring Reference
http://static.springframework.org/spring/docs/2.5.x/reference/

Más contenido relacionado

La actualidad más candente

Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5
Tuna Tore
 
springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892
Tuna Tore
 
Java Server Faces (JSF) - advanced
Java Server Faces (JSF) - advancedJava Server Faces (JSF) - advanced
Java Server Faces (JSF) - advanced
BG Java EE Course
 

La actualidad más candente (19)

SpringMVC
SpringMVCSpringMVC
SpringMVC
 
Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5
 
Spring 4 Web App
Spring 4 Web AppSpring 4 Web App
Spring 4 Web App
 
Spring MVC
Spring MVCSpring MVC
Spring MVC
 
Spring MVC
Spring MVCSpring MVC
Spring MVC
 
Spring Portlet MVC
Spring Portlet MVCSpring Portlet MVC
Spring Portlet MVC
 
Spring MVC 3.0 Framework (sesson_2)
Spring MVC 3.0 Framework (sesson_2)Spring MVC 3.0 Framework (sesson_2)
Spring MVC 3.0 Framework (sesson_2)
 
Spring annotation
Spring annotationSpring annotation
Spring annotation
 
Spring mvc
Spring mvcSpring mvc
Spring mvc
 
Spring Framework - MVC
Spring Framework - MVCSpring Framework - MVC
Spring Framework - MVC
 
springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892
 
Struts,Jsp,Servlet
Struts,Jsp,ServletStruts,Jsp,Servlet
Struts,Jsp,Servlet
 
Annotation-Based Spring Portlet MVC
Annotation-Based Spring Portlet MVCAnnotation-Based Spring Portlet MVC
Annotation-Based Spring Portlet MVC
 
ASP.NET Routing & MVC
ASP.NET Routing & MVCASP.NET Routing & MVC
ASP.NET Routing & MVC
 
Java Server Faces (JSF) - advanced
Java Server Faces (JSF) - advancedJava Server Faces (JSF) - advanced
Java Server Faces (JSF) - advanced
 
Backbone js
Backbone jsBackbone js
Backbone js
 
Spring mvc
Spring mvcSpring mvc
Spring mvc
 
Jinal desai .net
Jinal desai .netJinal desai .net
Jinal desai .net
 
Spray - Build RESTfull services in scala
Spray - Build RESTfull services in scalaSpray - Build RESTfull services in scala
Spray - Build RESTfull services in scala
 

Destacado

Spring mvc my Faviourite Slide
Spring mvc my Faviourite SlideSpring mvc my Faviourite Slide
Spring mvc my Faviourite Slide
Daniel Adenew
 
02 java spring-hibernate-experience-questions
02 java spring-hibernate-experience-questions02 java spring-hibernate-experience-questions
02 java spring-hibernate-experience-questions
Dhiraj Champawat
 
Spring 4 on Java 8 by Juergen Hoeller
Spring 4 on Java 8 by Juergen HoellerSpring 4 on Java 8 by Juergen Hoeller
Spring 4 on Java 8 by Juergen Hoeller
ZeroTurnaround
 

Destacado (15)

Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
 
Spring MVC - The Basics
Spring MVC -  The BasicsSpring MVC -  The Basics
Spring MVC - The Basics
 
Spring Framework - Core
Spring Framework - CoreSpring Framework - Core
Spring Framework - Core
 
Spring ppt
Spring pptSpring ppt
Spring ppt
 
Introduction to Spring Framework and Spring IoC
Introduction to Spring Framework and Spring IoCIntroduction to Spring Framework and Spring IoC
Introduction to Spring Framework and Spring IoC
 
Modeling and analysis
Modeling and analysisModeling and analysis
Modeling and analysis
 
Spring mvc my Faviourite Slide
Spring mvc my Faviourite SlideSpring mvc my Faviourite Slide
Spring mvc my Faviourite Slide
 
02 java spring-hibernate-experience-questions
02 java spring-hibernate-experience-questions02 java spring-hibernate-experience-questions
02 java spring-hibernate-experience-questions
 
Spring 3 Annotated Development
Spring 3 Annotated DevelopmentSpring 3 Annotated Development
Spring 3 Annotated Development
 
Spring Web Service, Spring JMS, Eclipse & Maven tutorials
Spring Web Service, Spring JMS, Eclipse & Maven tutorialsSpring Web Service, Spring JMS, Eclipse & Maven tutorials
Spring Web Service, Spring JMS, Eclipse & Maven tutorials
 
Spring @Transactional Explained
Spring @Transactional ExplainedSpring @Transactional Explained
Spring @Transactional Explained
 
What's new in Spring 3?
What's new in Spring 3?What's new in Spring 3?
What's new in Spring 3?
 
MVC Pattern. Flex implementation of MVC
MVC Pattern. Flex implementation of MVCMVC Pattern. Flex implementation of MVC
MVC Pattern. Flex implementation of MVC
 
Spring rest-doc-2015-11
Spring rest-doc-2015-11Spring rest-doc-2015-11
Spring rest-doc-2015-11
 
Spring 4 on Java 8 by Juergen Hoeller
Spring 4 on Java 8 by Juergen HoellerSpring 4 on Java 8 by Juergen Hoeller
Spring 4 on Java 8 by Juergen Hoeller
 

Similar a Introduction to Spring MVC

Spring 3: What's New
Spring 3: What's NewSpring 3: What's New
Spring 3: What's New
Ted Pennings
 
MVC & SQL_In_1_Hour
MVC & SQL_In_1_HourMVC & SQL_In_1_Hour
MVC & SQL_In_1_Hour
Dilip Patel
 

Similar a Introduction to Spring MVC (20)

Asp.NET MVC
Asp.NET MVCAsp.NET MVC
Asp.NET MVC
 
Asp.net mvc training
Asp.net mvc trainingAsp.net mvc training
Asp.net mvc training
 
Spring 3: What's New
Spring 3: What's NewSpring 3: What's New
Spring 3: What's New
 
Introducing Struts 2
Introducing Struts 2Introducing Struts 2
Introducing Struts 2
 
MVC & SQL_In_1_Hour
MVC & SQL_In_1_HourMVC & SQL_In_1_Hour
MVC & SQL_In_1_Hour
 
AJAX
AJAXAJAX
AJAX
 
AJAX
AJAXAJAX
AJAX
 
70562 (1)
70562 (1)70562 (1)
70562 (1)
 
What's Coming in Spring 3.0
What's Coming in Spring 3.0What's Coming in Spring 3.0
What's Coming in Spring 3.0
 
Integrating Wicket with Java EE 6
Integrating Wicket with Java EE 6Integrating Wicket with Java EE 6
Integrating Wicket with Java EE 6
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
 
Migrating from Struts 1 to Struts 2
Migrating from Struts 1 to Struts 2Migrating from Struts 1 to Struts 2
Migrating from Struts 1 to Struts 2
 
Backbone Basics with Examples
Backbone Basics with ExamplesBackbone Basics with Examples
Backbone Basics with Examples
 
Summer - The HTML5 Library for Java and Scala
Summer - The HTML5 Library for Java and ScalaSummer - The HTML5 Library for Java and Scala
Summer - The HTML5 Library for Java and Scala
 
Murach: How to transfer data from controllers
Murach: How to transfer data from controllersMurach: How to transfer data from controllers
Murach: How to transfer data from controllers
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotation
 
java ee 6 Petcatalog
java ee 6 Petcatalogjava ee 6 Petcatalog
java ee 6 Petcatalog
 
Retrofit Web Forms with MVC & T4
Retrofit Web Forms with MVC & T4Retrofit Web Forms with MVC & T4
Retrofit Web Forms with MVC & T4
 
Core Data with Swift 3.0
Core Data with Swift 3.0Core Data with Swift 3.0
Core Data with Swift 3.0
 
Apache Wicket Web Framework
Apache Wicket Web FrameworkApache Wicket Web Framework
Apache Wicket Web Framework
 

Más de Richard Paul (9)

Cucumber on the JVM with Groovy
Cucumber on the JVM with GroovyCucumber on the JVM with Groovy
Cucumber on the JVM with Groovy
 
Acceptance testing with Geb
Acceptance testing with GebAcceptance testing with Geb
Acceptance testing with Geb
 
Acceptance tests
Acceptance testsAcceptance tests
Acceptance tests
 
jQuery Behaviours
jQuery BehavioursjQuery Behaviours
jQuery Behaviours
 
Introduction to Spring's Dependency Injection
Introduction to Spring's Dependency InjectionIntroduction to Spring's Dependency Injection
Introduction to Spring's Dependency Injection
 
Unit Testing Fundamentals
Unit Testing FundamentalsUnit Testing Fundamentals
Unit Testing Fundamentals
 
Using Dojo
Using DojoUsing Dojo
Using Dojo
 
Javascript & Ajax Basics
Javascript & Ajax BasicsJavascript & Ajax Basics
Javascript & Ajax Basics
 
Mocking in Java with Mockito
Mocking in Java with MockitoMocking in Java with Mockito
Mocking in Java with Mockito
 

Último

EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 

Último (20)

Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 

Introduction to Spring MVC

  • 1. Spring MVC Richard Paul Kiwiplan NZ Ltd 27 Mar 2009
  • 2. What is Spring MVC Spring MVC is the web component of Spring's framework. Model - The data required for the request. View - Displays the page using the model. Controller - Handles the request, generates the model.
  • 4. Controller Interface public class MyController implements Controller { public ModelAndView handleRequest( HttpServletRequest request, HttpServletResponse response) { // Controller logic goes here } } This is the low level interface for controllers, most of the time you will not use the Controller interface directly. The ModelAndView, is an object that holds the model objects as well as the view required to be rendered (simplified definition).
  • 5. Controller Annotations @Controller public class ItemController { private ItemService itemService; @Autowired public ItemController(ItemService itemService) { this.itemService = itemService; } @RequestMapping(value=quot;viewItem.htmquot;, method=RequestMethod.GET) public Item viewItem(@RequestParam Long id) { return itemService.get(id); } } By convention a view with the name 'viewItem' (based on the request mapping URL) will be used to render the item.
  • 6. Session attributes @Controller @RequestMapping(quot;editItem.htmquot;) @SessionAttribute(quot;itemquot;) public class ItemEditorController { @RequestMapping(method=RequestMethod.GET) public String setupForm(@RequestParam Long itemId, ModelMap model) { Item item = ...; // Fetch item to edit model.addAttribute(quot;itemquot;, item); return quot;itemFormquot;; } @RequestMapping(method=RequestMethod.POST) public String processSubmit(@ModelAttribute(quot;itemquot;) Item item) { // Store item // ... return quot;redirect:/viewItem.htm?item=quot; + item.getId(); } } A GET to 'editItem.htm' adds the item with the given ID to the user's session. When a POST is made, this item is pulled from the session and provided as an argument to the processSubmit method.
  • 7. Flexible Method Arguments Methods mapped with @RequestMapping can have very flexible method signatures. Arguments handle(@RequestParam Long id) // 'id' parameter from request handle(@ModelAttribute Item item, BindingResult result) handle(ModelMap modelMap) // The model to populate handle(HttpSession session) // The user's session handle(Locale locale) // The locale (from the locale resolver) Return Type String // View name ModelAndView // Model objects and view name Item // Or other object, assumed to be the model object void // This method handles writing to the response itself http://static.springframework.org/spring/docs/2.5.x/reference/mvc.html#mvc-ann- requestmapping-arguments
  • 8. Testability We no longer need to pass in a HttpServletRequest when unit testing controllers. Most use cases can simply pass objects into the method. Examples show with Mockito. public Item view(@RequestParam Long id) { return itemService.get(id); } @Test public void viewWithValidId() { Item item = new Item(3l); when(itemService.get(3l)).thenReturn(item); assertEquals(item, controller.view(3l)); }
  • 9. Testability - with model attributes public String submitItem(@ModelAttribute Item item) { itemService.save(item); } @Test public void submitItem() { Item item = new Item(3l); controller.submitItem(item); verify(itemService.save(item)); } Previously the item would have been manually placed into a mock session under the 'item' key before calling the test.
  • 10. Binding In order to bind request parameters to Java objects, Spring uses PropertyEditors. Default Property Editors // For Strings ByteArrayPropertyEditor // For numbers, e.g. 4, 3.2 CustomNumberEditor ... Spring Provided Editors // For whitespace trimmed Strings StringTrimmerEditor // For file uploads FileEditor ... Custom property editors can be written. e.g. CategoryPropertyEditor for binding a Category.
  • 11. Example - CategoryPropertyEditor public class CategoryPropertyEditor extends PropertyEditorSupport { @Override public String getAsText() { Object value = getValue(); if (value == null) { return quot;quot;; } return ((Category) value).getId().toString(); } @Override public void setAsText(String text) { this.setValue(null); // Always clear existing value if (!StringUtils.isBlank(text)) { long id = Long.parseLong(text); this.setValue(categoryService.get(id)); } } } If an IllegalArgumentException is thown a binding error is stored and can be shown against the field in the form.
  • 12. Registering Property Editors Those property editors that aren't automatically wired up need to be initialised against the DataBinder. @InitBinder public void initBinder(DataBinder binder) { // Register a new editor each time as they are not thread safe binder.registerCustomEditor( Category.class, new CategoryPropertyEditor()); }
  • 13. Validation Spring provides a validation framework that is usually invoked in the controller layer. Also possible to register different editors based on the field. An alternative, which is still in draft form is JSR-303. It provides validation at a model level and can be used in the presentation, business & persistence layers.
  • 14. Example - ItemValidator Spring validator example. public class ItemValidator implements Validator { public boolean supports(Class clazz) { return Item.class.isAssignableFrom(clazz); } public void validate(Object target, Errors errors) { Item item = (Item) target; ValidationUtils.rejectIfEmpty(e, quot;namequot;, quot;name.emptyquot;); if (item.getCategory() == null) { e.rejectValue(quot;categoryquot;, quot;item.category.requiredquot;); } } } Errors are stored in the Errors object, if any errors are present, the form can be redisplayed with error messages instead of following the normal form submission.
  • 15. Views Spring supports a number of view technologies, the below example shows JSP with JSTL, specifically Spring's Form tags. <form:form method=quot;postquot; commandName=quot;itemquot;> <form:label path=quot;namequot;>Name</form:label> <form:input path=quot;namequot;/> <!-- Binding & Validation errors displayed here --> <form:error path=quot;namequot; cssClass=quot;errorquot;/> <!-- Show a select list of categories. Categories already set on the item are automatically selected --> <form:select path=quot;categoriesquot; items=quot;${allCategories}quot; itemValue=quot;idquot; itemLabel=quot;namequot;/> </form:form> Form tags are include for all HTML input types, e.g. form:radio, form:textarea
  • 16. Resolving Messages Spring resolves all messages using MessageSource interface. This message source is uses dot notation to access message coes. e.g. item.name.required Using springs default MessageSource, properties files using a specific locale are used. ApplicationResources.properties // Fall back ApplicationResources_en.properties // English ApplicationResources_es.properties // Spanish Custom implementations of MessageSource can be written. Useful if messages are pulled from a different backend e.g. XML
  • 17. AJAX Support AJAX support is limited in Spring 2.5 Generally use a separate library to generate JSON data for the controller to return. Hopefully better support will be coming with Spring 3.0 with new view types for XML, JSON, etc.